如何检查 Laravel Passport 中的身份验证状态?
How to check Auth status in Laravel Passport?
我正在尝试使用 Passport 验证检查 Laravel 中的用户验证状态。这是我正在尝试的:
api.php
Route::post('/check-auth-status', 'LoginController@checkUserAuthStatus')->middleware('auth:api');
登录控制器
public function checkUserAuthStatus(Request $request)
{
if($request->user() !== auth()->user())
return response()->json('Unauthorized user',401);
}
这里的问题是当用户注销时 url 没有命中,因为路由中有 middleware('auth:api')
,因此它向应用程序发送了未经授权的消息。
此外,Auth::check() 不起作用(总是 returns false)。
在这里做什么?或者有什么更好的主意吗?提前致谢!
就像你的代码一样,它不会在你应用中间件时工作,所以如果没有验证它不会进入内部checkUserAuthStatus
它将重定向到登录页面
你需要从 Handler.php
处理这个
将此功能添加到 Handler.php
use Illuminate\Auth\AuthenticationException;
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json('Unauthorized user',401)
: redirect('/login');
}
这里 $request->expectsJson()
表示如果请求 header
有 accept:application/json
那么它将 return json 响应您的自定义消息 Unauthorized user
我正在尝试使用 Passport 验证检查 Laravel 中的用户验证状态。这是我正在尝试的:
api.php
Route::post('/check-auth-status', 'LoginController@checkUserAuthStatus')->middleware('auth:api');
登录控制器
public function checkUserAuthStatus(Request $request)
{
if($request->user() !== auth()->user())
return response()->json('Unauthorized user',401);
}
这里的问题是当用户注销时 url 没有命中,因为路由中有 middleware('auth:api')
,因此它向应用程序发送了未经授权的消息。
此外,Auth::check() 不起作用(总是 returns false)。
在这里做什么?或者有什么更好的主意吗?提前致谢!
就像你的代码一样,它不会在你应用中间件时工作,所以如果没有验证它不会进入内部checkUserAuthStatus
它将重定向到登录页面
你需要从 Handler.php
将此功能添加到 Handler.php
use Illuminate\Auth\AuthenticationException;
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json('Unauthorized user',401)
: redirect('/login');
}
这里 $request->expectsJson()
表示如果请求 header
有 accept:application/json
那么它将 return json 响应您的自定义消息 Unauthorized user