gpt4 book ai didi

laravel - 处理 laravel 中的 jwt auth 错误

转载 作者:行者123 更新时间:2023-12-03 07:40:14 24 4
gpt4 key购买 nike


我正在开发一个rest api 项目。
我正在努力解决一个问题。当我收到 token 过期错误时,生成的代码将如下所示:

public function authenticate(Request $request){
$this->checkForToken($request);

try {
if (! $this->auth->parseToken()->authenticate()) {
throw new UnauthorizedHttpException('jwt-auth', 'User not found');
}
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
}
}

这段代码写在这个文件中:

vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php


如何将其作为 JSON 类型返回?

最佳答案

App\Exceptions\Handler 类的渲染方法中捕获异常并返回 json 格式的响应:

// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...

public function render($request, Exception $exception)
{

// if your api client has the correct content-type this expectsJson()
// should work. if not you may use $request->is('/api/*') to match the url.


if($request->expectsJson())
{

if($exception instanceof UnauthorizedHttpException) {

return response()->json('Unauthorized', 403);

}

}

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

}

关于laravel - 处理 laravel 中的 jwt auth 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650422/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com