【问题标题】:Customize Laravel Passport response unauthenticated自定义 Laravel Passport 响应未经身份验证
【发布时间】:2019-10-07 10:54:55
【问题描述】:

目前,我使用我在 Laravel 中使用护照功能制作的 api 具有登录、注册、更新和删除功能。一切正常,插入数据并使用此 api 从数据库中获取数据。现在我想知道,如何在令牌过期时自定义api的响应。令牌的到期也可以正常工作。它会自动显示此消息

{ "message": "Unauthenticated" }

这是受我的 Oauth 令牌保护的路由代码,如果用户没有先登录,则用户未通过身份验证以浏览路由

 Route::middleware('auth:api')->get('/user', function (Request $request){return $request->user();});



Route::post('/timekeeping','Auth\Api\AuthController@timekeeping');

Route::post('/login','Auth\Api\AuthController@login');

 Route::middleware('auth:api')->group(function () {Route::post('/timekeeping_app','Auth\Api\AuthController@timekeeping_app');

Route::post('/logout','Auth\Api\AuthController@logout');

Route::post('/register','Auth\Api\AuthController@register');

Route::post('/show_dtr_list','Auth\Api\AuthController@show_dtr_list');

Route::post('/update','Auth\Api\AuthController@update');

Route::post('/delete','Auth\Api\AuthController@delete');

 });

这就是每当用户成功登录、注册甚至注销其帐户时我的响应方式。

return response(['status'=>'oK','message'=>'Successful!']);

我想要的是每次用户使用过期令牌时。 api 应该响应类似这样的内容

{ "message": "Token is expired" }

不只是

{ "message": "Unathenticated" }

一些线程讨论了我需要覆盖 laravel 的一些功能,但我不知道从哪里以及如何开始。

【问题讨论】:

  • 有关于这种情况的更新吗?

标签: php laravel-passport


【解决方案1】:

这就是我解决它的方法。如果您使用的是 Laravel 5.5 或更高版本,您可以通过编辑 app/Exceptions/Handler.php 添加以下内容来覆盖默认异常处理程序:

use Illuminate\Auth\AuthenticationException;

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        $json = [
            'isAuth'=>false,
            'message' => $exception->getMessage()
        ];
        return response()
            ->json($json, 401);
    }
    $guard = array_get($exception->guards(),0);
    switch ($guard) {
        default:
            $login = 'login';
            break;
    }
    return redirect()->guest(route($login));
}

在 JSON 返回中,您可以根据需要添加任何参数。

【讨论】:

  • 调用未定义函数 App\Exceptions\array_get()
  • 重要的一点是,在请求的头部,我们应该有Expect: application/json。否则if 条件将不起作用。
【解决方案2】:

这个解决方案对我有用,在 Laravel Docs 中找到。 您可以像这样覆盖 Handler 中未经身份验证的函数:

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
                ? response()->json(['message' => $exception->getMessage()], 401)
                : redirect()->guest(route('login'));
}

然后,处理并提供您想要的响应。

不要忘记在 Handle.php 文件中也导入这个:

use Illuminate\Auth\AuthenticationException;

我希望它对你有好处!

【讨论】:

  • 这只是去年已经接受的答案的精简版。
【解决方案3】:

在 Handler.php 文件顶部添加以下内容:

use Illuminate\Auth\AuthenticationException;

只需添加以下功能:

protected function unauthenticated($request, AuthenticationException $exception)
{
   if ($request->expectsJson()){
       return response()->json(['message' => "Token is expired"], 401);
   }

   return parent::render($request, $exception); // TODO: Change theautogenerated stub
}

【讨论】:

    【解决方案4】:

    覆盖 auth:api 中间件,并对其进行相应修改以提供所需的响应。

    【讨论】:

      【解决方案5】:

      1- 创建新的中间件 UserAccessible

       <?php
      
      namespace App\Http\Middleware;
      
      use Closure;
      use Illuminate\Support\Facades\Auth;
      
      class UserAccessible
      {
      
          /**
           * Handle an incoming request.
           *
           * @param  \Illuminate\Http\Request  $request
           * @param  \Closure  $next
           * @return mixed
           */
          public function handle($request, Closure $next)
          {
      
              $isAuth = Auth::guard('api')->check();
      
              if(!$isAuth){
                  // redirect page or error.
      
                  $code = 401;
      
                  $output = ['code' => $code,
                      'status' => false,
                      'msg' => 'Unauthenticated',
                      'data' => []];
      
                  return response()->json($output, $code);
              }
      
              return $next($request);
          }
      }
      

      2- 在 Kernal.php 中定义中间件

      protected $routeMiddleware = [
          'user_accessible' => \App\Http\Middleware\UserAccessible::class,
      ];
      

      }

      3- 在控制器中

      class XController extends Controller
      {
      
          /**
           * Create a new controller instance.
           *
           * @return void
           */
          public function __construct()
          {
              $this->middleware('user_accessible');
          }
      

      或在路线中

      Route::middleware('user_accessible')->get('/user', function (Request $request) {
          return $request->user();
      }); 
      

      【讨论】:

        猜你喜欢
        • 2020-12-18
        • 1970-01-01
        • 2018-01-05
        • 2021-01-01
        • 2017-09-01
        • 2018-05-02
        • 1970-01-01
        • 2018-10-15
        • 2020-08-26
        相关资源
        最近更新 更多