Laravel JWT Exception Handling

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

 批注 2020-04-17 013040


也可以在app\Exceptions\Handler.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 App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\JWTAuth;


class JWT
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $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' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
	'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
];

批注 2020-04-17 014502

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

猜你喜欢

转载自www.cnblogs.com/dzkjz/p/12717137.html