Search code examples
laravelvue.jssingle-page-applicationlaravel-sanctum

Laravel Vue SPA using Sanctum response Unauthorized


The Sanctum Auth system on my local machine works well and I have no errors. But my deployed app is having trouble with authorizing a user. When I login it sends a request to get the user data then redirects. After auth completes you are redirected and the app make a GET request for more data. This GET route is guarded using laravel sanctum. But the backend is not registering that the user has made a successful login attempt so it sends a 401 Unauthorized error. Here is some code...

loadUser action from store.js

actions: {
    async loadUser({ commit, dispatch }) {
        if (isLoggedIn()) {
            try {
                const user = (await Axios.get('/user')).data;
                commit('setUser', user);
                commit('setLoggedIn', true);
            } catch (error) {
                dispatch('logout');
            }
        }
    },
}

Route Guard on the routs.js checking to see isLoggedIn (which is just a boolean store locally)

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
    // if (to.meta.requiresAuth) {
        if (isLoggedIn()) {
            next();
        } else {
            next({
                name: 'home'
            });
        }
    } else {
        next();
    }
})

It was pointed out that I had forgotten the withCredetials setting for axios in bootstrap.js. I made this addition but my issue still remains.

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;

Route middleware guard on the server side (this is where the request is getting turned away)

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('trucks', 'Api\TruckController');
});

In the laravel cors.php config file I changed the "supports_credentials" from false to true

'supports_credentials' => true,

It seems to me that the cookie information is not being over the api call (but I'm really not sure). This setup is working on my local machine but not on the server that I have deployed to.


Solution

  • Needed to add an environment variable to the .env file for SANCTUM_STATEFUL_DOMAINS and made that equal the domain name.

    In the laravel sanctum.php config file...

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1')),