如何有选择地使用 Laravel Sanctum 进行身份验证?

How to optionally authenticate with Laravel Sanctum?

我正在使用 Laravel Sanctum 对用户进行身份验证。我想要一条可供访客和登录用户访问的路线。登录用户在授权 header.

中发送一个 API 令牌

我试过在没有身份验证的情况下创建路由,但那样我就看不到登录用户了。

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

我也尝试过使用 auth:sanctum 中间件,但那样访客无法访问该页面。

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

解决方案应该 return true with auth headers, and false without auth headers.

Auth 默认使用 web 守卫。在/config/auth.php中将其更改为sanctum

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