自定义 Laravel Passport 响应未经身份验证

Kin*_* RG 4 php laravel-passport

目前,我使用护照功能在 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');

 });
Run Code Online (Sandbox Code Playgroud)

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

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

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

{ "message": "Token is expired" }

不只是

{ "message": "Unathenticated" }

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

Er *_*wal 5

这是我解决它的方法。如果您使用的是 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));
}
Run Code Online (Sandbox Code Playgroud)

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


小智 0

覆盖auth:api中间件,并相应地修改它以给出您想要的响应。