0

我想用 laravel sanctum 在 SPA 中进行身份验证。我设置了如下代码的环境。但是在我登录和下一个 api 请求后,就会发生错误。为什么?。第一个请求返回 X-CSRF-TOKEN 。据我所知,axios在我登录后会自动提交X-CSRF-TOKEN。请给我建议。

api.php

Route::middleware('auth:sanctum')->get('/sanctum/test', function (Request $request) {
  return 'Nice!';
});

Route::post('/login', 'Auth\LoginController@login');

LoginController 的登录方法

  public function login(Request $request)
  {
    $this->validateLogin($request);

    $user = User::where('number', $request->login_id)->orWhere('email', $request->login_id)->first();

    if (!$user || !Hash::check($request->password, $user->password)) {
      throw ValidationException::withMessages([
        'login_id' => ['uncorrect'],
      ]);
    } else {
      return 'success';
    }
}

登录.tsx

  function Submit() {
    axios.get('/sanctum/csrf-cookie').then(response => {
      console.log(response);
    axios
      .post("/api/login", {
        login_id: loginID,
        password: password,
      })
      .then(response => {
        console.log(response);
        axios.get('/api/sanctum/test').then(res => {
        console.log(res);
       })
      })
   });
  }

卡内尔.php

  protected $middlewareGroups = [
    'web' => [
      \App\Http\Middleware\EncryptCookies::class,
      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
      \Illuminate\Session\Middleware\StartSession::class,
      // \Illuminate\Session\Middleware\AuthenticateSession::class,
      \Illuminate\View\Middleware\ShareErrorsFromSession::class,
      \App\Http\Middleware\VerifyCsrfToken::class,
      \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
      EnsureFrontendRequestsAreStateful::class,
      'throttle:60,1',
      \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
  ];

数据库.php

APP_NAME=Laravel
APP_ENV=local
APP_KEY=secret
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=secret
DB_USERNAME=root
DB_PASSWORD=secret

SESSION_DRIVER=file
SANCTUM_STATEFUL_DOMAINS=localhost:8000
SESSION_DOMAIN=localhost

在此处输入图像描述

4

1 回答 1

0

Route::middleware('auth:sanctum')需要Authorization:<Bearer-Token>标题。Authorization为连续请求设置标头将起作用。

于 2020-12-15T07:04:31.013 回答