Laravel Vue SPA using Sanctum response Unauthorized

£可爱£侵袭症+ 提交于 2020-04-30 07:14:08

问题


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.


回答1:


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')),


来源:https://stackoverflow.com/questions/61317741/laravel-vue-spa-using-sanctum-response-unauthorized

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!