我们使用Composer安装jwt扩展包:
composer require tymon/jwt-auth 0.5.*
安装完成后,需要在 config/app.php 中注册相应的服务提供者:
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class
'aliases' => [
'JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
],
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
php artisan jwt:generate
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
需要在路由组添加 :
['middleware' => ['jwt.auth','jwt.refresh']
1、添加一个 Middleware
可以使用命令行添加:php artisan make:middleware GetUserFromToken 此命令将会 在 app/Http/Middleware 目录内置立一个名称GetUserFromToken 的类。
authenticate()) {
return response()->json([
'errcode' => 400004,
'errmsg' => 'user not found'
], 404);
}
} catch (TokenExpiredException $e) {
return response()->json([
'errcode' => 400001,
'errmsg' => 'token expired'
], $e->getStatusCode());
} catch (TokenInvalidException $e) {
return response()->json([
'errcode' => 400003,
'errmsg' => 'token invalid'
], $e->getStatusCode());
} catch (JWTException $e) {
return response()->json([
'errcode' => 400002,
'errmsg' => 'token absent'
], $e->getStatusCode());
}
return $next($request);
}
}
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
'jwt.api.auth' => \App\Http\Middleware\GetUserFromToken::class, //新增注册的中间件
];
['middleware' => 'jwt.api.auth']