如何自定义Laravel Sanctum的401未授权响应返回格式
Laravel Sanctum 自定义401未授权响应实现方法
实现逻辑
Laravel 所有身份认证(包括Sanctum)的未认证异常都会抛出Illuminate\Auth\AuthenticationException,我们只需要在全局异常处理中捕获该异常,返回自定义的JSON结构即可。
操作步骤
针对 Laravel 8/9/10 版本
- 打开项目下的
app/Exceptions/Handler.php文件,在顶部引入依赖类:
use Illuminate\Auth\AuthenticationException; use Illuminate\Http\Request; use Throwable;
- 找到
render方法,添加异常捕获判断:
public function render(Request $request, Throwable $exception) { // 捕获未认证异常,且请求期望返回JSON if ($exception instanceof AuthenticationException && $request->expectsJson()) { return response()->json([ 'data' => [ 'code' => 401, 'book' => null, 'success' => false, 'error' => [ 'message' => 'Not authenticated' ] ] ], 401); } return parent::render($request, $exception); }
针对 Laravel 11 版本
Laravel 11 默认移除了Handler.php,可以直接在bootstrap/app.php中配置异常捕获规则:
- 打开
bootstrap/app.php文件,找到withExceptions配置段,添加如下逻辑:
use Illuminate\Auth\AuthenticationException; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Http\Request; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', api: __DIR__.'/../routes/api.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // }) ->withExceptions(function (Exceptions $exceptions) { $exceptions->render(function (AuthenticationException $e, Request $request) { if ($request->expectsJson()) { return response()->json([ 'data' => [ 'code' => 401, 'book' => null, 'success' => false, 'error' => [ 'message' => 'Not authenticated' ] ] ], 401); } }); })->create();
注意事项
- 发送API请求时需要携带
Accept: application/json请求头,否则Laravel不会判定为JSON请求,会默认跳转登录页而非返回JSON响应。 - 该配置对所有Laravel身份认证守卫生效,无需单独针对Sanctum做额外适配。
内容的提问来源于stack exchange,提问作者Denny Kurniawan
相关产品推荐
相关产品推荐

