[英]How to optionally authenticate with Laravel Sanctum?
I'm using Laravel Sanctum to authenticate users.我正在使用Laravel Sanctum对用户进行身份验证。 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.
登录用户在 Authorization 标头中发送 API 令牌。
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.我也试过使用
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
The solution should return true with auth headers, and false without auth headers.解决方案应该使用 auth 标头返回 true,而在没有 auth 标头的情况下返回 false。
Auth
is using the web
guard by default. Auth
默认使用web
防护。 Change it to sanctum
in /config/auth.php
:在
/config/auth.php
中将其更改为sanctum
:
'defaults' => [
// 'guard' => 'web',
'guard' => 'sanctum',
'passwords' => 'users',
],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.