6

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.

4
  • Try return Auth::guard('web')->check(); for me?
    – ceejayoz
    Commented Nov 10, 2021 at 22:01
  • @ceejayoz It returned false regardless of auth headers. I may have misconfigured something, because I only use this laravel app for APIs. And Auth::guard('api') returns errors. Commented Nov 11, 2021 at 6:05
  • 2
    if you do auth('sanctum')->user(), you can get the user. It will return null if the user is not logged in. ` Commented Apr 25, 2022 at 19:57
  • Auth::guard('sanctum')->user() worked with me. Commented Mar 10 at 8:53

2 Answers 2

5

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

And make sure NOT to use auth:sanctum middleware

-1

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

'defaults' => [
    // 'guard' => 'web',
    'guard' => 'sanctum',
    'passwords' => 'users',
],
1
  • This option controls the default authentication guard for both api and web group. so this can break the web group routes auth check. Commented Mar 10 at 9:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.