Laravel 11 Passport token错误处理:OAuthServerException返回JSON失败
解决Laravel Passport无有效Token时返回JSON错误响应的问题
1. 先修复异常处理中的类引入错误
你代码里用了Request $request但未引入对应的类,这直接导致了500内部服务器错误。在bootstrap/app.php顶部添加以下引入:
use Illuminate\Http\Request;
2. 完善异常捕获逻辑
仅捕获OAuthServerException不够,还需要处理API请求下的通用未认证异常,同时要确保只针对API请求返回JSON响应,避免影响Web路由的跳转行为。修正后的异常处理代码如下:
->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (Throwable $e, Request $request) { // 仅处理API请求的异常 if ($request->isApi() || $request->expectsJson()) { // 处理Passport的OAuth服务异常 if ($e instanceof OAuthServerException) { return response()->json([ 'error' => $e->getErrorType(), 'message' => $e->getMessage(), 'hint' => $e->getHint(), ], $e->getHttpStatusCode()); } // 处理通用未认证异常(比如未携带Token的情况) if ($e instanceof \Illuminate\Auth\AuthenticationException) { return response()->json([ 'error' => 'unauthenticated', 'message' => '未提供有效Token,请重新登录' ], 401); } } }); })
3. 确认API路由使用正确的认证中间件
在routes/api.php中,需要认证的路由组必须使用auth:api中间件:
Route::middleware('auth:api')->group(function () { // 这里放置需要认证的API路由 Route::get('/user', function (Request $request) { return $request->user(); }); });
4. 检查前端请求头设置
前端发起请求时需携带Accept: application/json头,Laravel识别到是JSON请求后,会优先返回JSON格式的响应。
额外排查点
如果问题仍存在,检查config/auth.php中的API guard配置是否正确指向Passport:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
内容的提问来源于stack exchange,提问作者Shafi Asharaf
相关产品推荐
相关产品推荐

