Home > Net >  How to optionally authenticate with Laravel Sanctum?
How to optionally authenticate with Laravel Sanctum?

Time:11-15

I'm using Laravel Sanctum to authenticate users. I'd like to have a route that can be accessed by guests and logged in users. Logged in users send an API Token in the Authorization header.

I've tried making a route without authentication, but that way I can't see the logged in user.

Route::get('noauth', function() {
  return Auth::check();
});

GET /noauth with auth header returns false, user is not logged in
GET /noauth without auth header returns false, user is not logged in

I've also tried using auth:sanctum middleware, but that way guests can't access the page.

Route::get('yesauth', function() {
  return Auth::check();
})->middleware('auth:sanctum');

GET /yesauth with auth header returns true, the user is logged in
GET /yesauth withouth auth header returns 401, unauthorized

The solution should return true with auth headers, and false without auth headers.

CodePudding user response:

Auth is using the web guard by default. Change it to sanctum in /config/auth.php:

'defaults' => [
    // 'guard' => 'web',
    'guard' => 'sanctum',
    'passwords' => 'users',
],
  • Related