How to optionally authenticate with Laravel Sanctum?
Asked Answered
T

2

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.

Taverner answered 10/11, 2021 at 21:56 Comment(4)
Try return Auth::guard('web')->check(); for me?Erenow
@Erenow 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.Labe
if you do auth('sanctum')->user(), you can get the user. It will return null if the user is not logged in. `Houlberg
Auth::guard('sanctum')->user() worked with me.Cauley
T
-1

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

'defaults' => [
    // 'guard' => 'web',
    'guard' => 'sanctum',
    'passwords' => 'users',
],
Taverner answered 14/11, 2021 at 16:52 Comment(1)
This option controls the default authentication guard for both api and web group. so this can break the web group routes auth check.Cauley
W
3

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

Wit answered 30/8, 2023 at 2:38 Comment(0)
T
-1

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

'defaults' => [
    // 'guard' => 'web',
    'guard' => 'sanctum',
    'passwords' => 'users',
],
Taverner answered 14/11, 2021 at 16:52 Comment(1)
This option controls the default authentication guard for both api and web group. so this can break the web group routes auth check.Cauley

© 2022 - 2025 — McMap. All rights reserved.