Laravel JWT Exception Handling
如果我们有一些比较常见的JWT exception 可以 try catch处理
也可以在app\Exceptions\Handler.php的render方法内部处理:
如:
有多少加多少即可!但是如果需要很有针对性的返回信息,用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', ];
需要用这个中间件的地方,就用jwt.auth即可,然后所有的JWT相关的Exception都可以在这个中间件中处理。