如何在令牌过期时自定义 laravel 护照响应

how to customize laravel passport respone on token expire

如何更改 laravel 护照回复 access_token 从

过期
{
    "message": "Unauthenticated."
}

{
    "type": "error",
    "status": 401,
    "message": "Access Token expires",
}

您可以在 App\Exceptions\Handler.php class 中添加自定义异常处理。如果尚不存在,请添加以下功能。您基本上是在捕获身份验证异常,并向其添加您自己的转换。

use Illuminate\Http\Response;
use Illuminate\Auth\AuthenticationException;

public function render($request, Throwable $e)
{
    if ($e instanceof AuthenticationException) {
        return response()->json(
            [
                'type' => 'error',
                'status' => Response::HTTP_UNAUTHORIZED,
                'message' => 'Access Token expires',
            ],
            Response::HTTP_UNAUTHORIZED
        );
    }

    return parent::render($request, $e);
}