如何自定义Laravel Passport访问令牌过期时的响应格式
Laravel Passport 自定义access_token过期响应教程
实现思路
Laravel 中所有认证相关的异常最终都会交由 App\Exceptions\Handler 类统一渲染,我们只需要在该类中对Passport触发的401认证异常做自定义处理即可。
操作步骤
- 打开项目目录下的
app/Exceptions/Handler.php文件 - 重写类中的
render方法,加入认证异常的自定义返回逻辑,参考代码如下:
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Illuminate\Auth\AuthenticationException; use Throwable; class Handler extends ExceptionHandler { // 原有其他属性和方法保持不变 public function render($request, Throwable $e) { // 仅针对JSON请求的认证异常做处理 if ($e instanceof AuthenticationException && $request->expectsJson()) { // 可选:判断是否是token过期导致的认证失败,不需要区分可以删掉这段判断直接写固定message $isExpired = false; if ($request->hasHeader('Authorization') && str_starts_with($request->header('Authorization'), 'Bearer ')) { try { $tokenPayload = explode('.', explode(' ', $request->header('Authorization'))[1]); $token = \Laravel\Passport\Token::find(base64_decode($tokenPayload[1])->jti ?? null); $isExpired = $token?->expires_at?->isPast(); } catch (\Exception $exception) {} } return response()->json([ 'type' => 'error', 'status' => 401, 'message' => $isExpired ? 'Access Token expires' : 'Unauthenticated.' ], 401); } return parent::render($request, $e); } }
注意事项
- 调用API时需要在请求头中加入
Accept: application/json,否则Laravel不会识别为JSON请求,不会触发自定义返回逻辑 - 如果你不需要区分token过期和其他未认证场景(比如token无效、未传token),可以直接写死message为
Access Token expires即可
内容的提问来源于stack exchange,提问作者swatantra
相关产品推荐
相关产品推荐

