我正在开发一个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/