0

我正在尝试使用 Laravel 8 + Sanctum 和 Vue3 + Vuex3 创建 CRUD。我使用了很多教程,但没有像我预期的那样工作。

对我来说最不可理解的是Sanctum and error:“未授权”

在 Login 组件中查看我的登录功能:

async login() {
            await axios.get('/sanctum/csrf-cookie')
            await axios.post('/api/login', this.form).then((response) => {
                this.signIn(response.data)
            }).catch((response) => {
                this.responseText = 'Niepoprawny e-mail lub hasło.'
            })
        },

Vuex 身份验证

mutations: {
        SET_TOKEN(state, value) {
            state.token = 'Bearer '+value
        },
        SET_AUTHENTICATED(state, value) {
            state.authenticated = value
        },
        SET_USER(state, value) {
            state.user = value
        }
    },
    actions: {
        login({commit}, data) {
            commit('SET_TOKEN', data.access_token)
            commit('SET_USER', data.user)
            commit('SET_AUTHENTICATED', true)

            router.push({ name: 'Dashboard' })
        },
        logout({commit}) {
            commit('SET_USER', {})
            commit('SET_AUTHENTICATED', false)

            router.push({ name: 'Login' })
        }
    }

现在,成功登录后,我想去仪表板并查看用户列表。仪表板组件:

async getUsers() {
            await axios.get('/sanctum/csrf-cookie')
            await axios.get('/api/dashboard/users',
            ).then(response => {
                this.users = response.data;
            }).catch((response) => {
                alert(response)
            });
        },

在这里我有圣所错误。但!尝试使用登录期间获得的令牌作为 axios 的标头来解决此问题:

async getUsers() {
            const config = {
                headers: { Authorization: this.token }
            };
            // await axios.get('/sanctum/csrf-cookie')
            await axios.get('/api/dashboard/users', config
            ).then(response => {
                this.users = response.data;
            }).catch((response) => {
                alert(response)
            });
        },

一切都开始了。为什么?为什么所有带有 sanctum 的教程都只有 axios.get /sanctum/scrf-cookie 不起作用?我错了什么?如果我必须在登录后从数据库中获取令牌,我应该使用 sanctum 吗?我很难理解这一点。

我的 api Laravel 路由器:

Route::post('register', [AuthController::class, 'register']);
Route::post('login', [AuthController::class, 'login']);
Route::post('password', [AuthController::class, 'resetPassword']);
// get or post? i don't send anything
Route::post('logout', [AuthController::class, 'logout']);

Route::middleware('auth:sanctum')->group(function () {
    Route::prefix('/')->group(function () {
        Route::get('', [HomeController::class, 'index']);
    });
    Route::prefix('/dashboard')->group(function () {
        Route::get('', [DashboardController::class, 'index']);
        Route::get('/users', [UserController::class, 'index']);
    });

    Route::put('/user', [UserController::class, 'store']);
    Route::delete('/user/{id}', [UserController::class, 'destroy']);
});

Vue路由器:

const Routes = [
    {
        name: 'Login',
        path: '/login',
        component: Login,
        meta: {
            middleware: "guest",
            title: "Login"
        }
    },
   {
        name: 'Home',
        path: '/',
        component: Home,
        meta: {
            middleware: "auth",
            title: "Home"
        },
    },
    {
        name: 'Dashboard',
        path: '/dashboard',
        component: Dashboard,
        meta: {
            middleware: "auth",
            title: "Dashboard"
        },
    },
...

我还设置了 cors、sanctum config 并设置了 SESSION_DRIVER 等。

.env:

SESSION_DRIVER=cookie 
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8000

cors.php

'paths' => [
        'api/*',
        '/login',
        '/logout',
        '/sanctum/csrf-cookie'
    ],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

圣所.php

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

 'guard' => ['web'],

有人可以帮我理解吗?

问候

4

0 回答 0