Laravel JWT Exception Handling

如果我们有一些比较常见的JWT exception 可以 try catch处理

 批注 2020-04-17 013040


也可以在appExceptionsHandler.php的render方法内部处理:

批注 2020-04-17 013145

如:

批注 2020-04-17 013527

有多少加多少即可!但是如果需要很有针对性的返回信息,用try catch比较合适,render方法里比较粗糙但是简单。

更多可以参考:

Retreiving the Authenticated user from a token

还可以添加一个中间件:

执行:

php artisan make:middleware JWT

JWT.php:

<?php

namespace AppHttpMiddleware;

use Closure;
use TymonJWTAuthJWTAuth;


class JWT
{
    /**
     * Handle an incoming request.
     *
     * @param IlluminateHttpRequest $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        JWTAuth::parseToken()->authenticate();

        return $next($request);
    }
}

然后注册这个中间件:

To use the middlewares you will have to register them in app/Http/Kernel.php under the $routeMiddleware property:

protected $routeMiddleware = [
	...
	'jwt.auth' => 'TymonJWTAuthMiddlewareGetUserFromToken',
	'jwt.refresh' => 'TymonJWTAuthMiddlewareRefreshToken',
];

批注 2020-04-17 014502

需要用这个中间件的地方,就用jwt.auth即可,然后所有的JWT相关的Exception都可以在这个中间件中处理。

原文地址:https://www.cnblogs.com/dzkjz/p/12717137.html