Why did sanctum middleware return error (unauthorized 401) in Laravel?

988 Views Asked by At

I I want to make authentication in SPA with laravel sanctum. And I seted enviroment like below code. But after I logged in and next api request, error happen. Why?. First request returned X-CSRF-TOKEN . And As far as I know, axios submit X-CSRF-TOKEN automatically after i loggin. Please give me advice.

api.php

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

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

LoginController's login method

  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';
    }
}

Sign_in.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);
       })
      })
   });
  }

Karnel.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,
    ],
  ];

database.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

enter image description here

1

There are 1 best solutions below

0
On

In Route::middleware('auth:sanctum') needs Authorization:<Bearer-Token> header. Setting Authorization header for the consecutive request will work.