4

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.

Gergő Gutyina
  • 129
  • 1
  • 12

2 Answers2

0

You can check if there is token in the request.

If token is present try to get the user from Sanctum auth guard and assign it as the current user.

if (request()->bearerToken() && $user = Auth::guard('sanctum')->user()) {
    Auth::setUser($user);
}

return Auth::check() // false for guest users, true if valid token present
antja0
  • 39
  • 1
  • 3
-1

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

'defaults' => [
    // 'guard' => 'web',
    'guard' => 'sanctum',
    'passwords' => 'users',
],
Gergő Gutyina
  • 129
  • 1
  • 12