【问题标题】:How to check Auth status in Laravel Passport?如何在 Laravel Passport 中检查身份验证状态?
【发布时间】:2021-02-15 05:56:01
【问题描述】:

我正在尝试使用 Passport auth 检查 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);
}

这里的问题是由于middleware('auth:api') 在路由中,当用户注销时,url 没有命中,所以它向应用程序发送了未经授权的消息。 此外,Auth::check() 不起作用(总是返回 false)。

在这里做什么?还是有更好的主意?提前致谢!

【问题讨论】:

    标签: laravel laravel-7 laravel-passport


    【解决方案1】:

    就像你的代码一样,它不会在你使用中间件时工作,所以如果没有验证它不会进入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() 表示如果请求headeraccept:application/json 那么它将返回带有您的自定义消息Unauthorized user 的json 响应

    【讨论】:

    • 仅此而已吗?我需要在 api.php 或控制器中保留任何内容吗?
    • 不,它将是全局 api AuthenticationException handler
    • return $request->expectsJson()? response()->json(['Unauthorized user'], 401 : response()->json(['Authorized user'], 201); 它返回 404 not found 给应用程序。
    • 404 表示您的 url 不在您的应用程序中,此代码为handel AuthenticationException
    • 正如你所说,我从 api.php 中删除了路由,只保留了 Handler.php 上的函数!
    猜你喜欢
    • 2021-01-29
    • 2017-05-13
    • 1970-01-01
    • 2017-12-09
    • 2016-03-16
    • 2018-09-23
    • 2020-08-17
    • 1970-01-01
    • 2017-07-28
    相关资源
    最近更新 更多