我正在尝试使用 Passport 身份验证在 Laravel 中检查用户身份验证状态。这是我正在尝试的:
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);
}
这里的问题是当用户由于路由中的 middleware('auth:api')
而注销时,url 没有命中,因此它向应用程序发送了未经授权的消息。
此外,Auth::check() 不起作用(总是返回 false)。
在这里做什么?或者有什么更好的主意?提前致谢!
答案 0 :(得分:1)
就像你的代码一样,它不会像你使用中间件那样工作,所以如果不是 auth 它不会进入 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
那么它将返回带有您的自定义消息 Unauthorized user
的 json 响应