您好,欢迎访问一九零五行业门户网

laravel安装jwt-auth及验证(实例)

laravel 安装jwt-auth及验证
1、使用composer安装jwt,cmd到项目文件夹中;
composer require tymon/jwt-auth 1.0.*(这里版本号根据自己的需要写)
安装jwt ,参考官方文档https://jwt-auth.readthedocs.io/en/docs/laravel-installation/
2、如果laravel版本低于5.4
打开根目录下的config/app.php 
在'providers'数组里加上tymon\jwtauth\providers\laravelserviceprovider::class,
'providers' => [ ... tymon\jwtauth\providers\laravelserviceprovider::class,]
3、在 config 下增加一个 jwt.php 的配置文件
php artisan vendor:publish --provider=tymon\jwtauth\providers\laravelserviceprovider
4、在 .env 文件下生成一个加密密钥,如:jwt_secret=foobar
php artisan jwt:secret
5、在user模型中写入下列代码
<?phpnamespace app\model;use tymon\jwtauth\contracts\jwtsubject;use illuminate\notifications\notifiable;use illuminate\foundation\auth\user as authenticatable;class user extends authenticatable implements jwtsubject{ // rest omitted for brevity protected $table="user"; public $timestamps = false; public function getjwtidentifier() { return $this->getkey(); } public function getjwtcustomclaims() { return []; }}
6、注册两个 facade
config/app.php
'aliases' => [ ... // 添加以下两行 'jwtauth' => 'tymon\jwtauth\facades\jwtauth', 'jwtfactory' => 'tymon\jwtauth\facades\jwtfactory',],
7、修改 auth.php
config/auth.php
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', // 原来是 token 改成jwt 'provider' => 'users', ],],
8、注册路由
route::group([ 'prefix' => 'auth'], function ($router) { $router->post('login', 'authcontroller@login'); $router->post('logout', 'authcontroller@logout');});
9、创建token控制器
php artisan make:controller authcontroller
代码如下:
<?phpnamespace app\http\controllers;use app\model\user;use illuminate\http\request;use tymon\jwtauth\facades\jwtauth;class authcontroller extends controller{ /** * create a new authcontroller instance. * * @return void */ public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } /** * get a jwt via given credentials. * * @return \illuminate\http\jsonresponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth('api')->attempt($credentials)) { return response()->json(['error' => 'unauthorized'], 401); } return $this->respondwithtoken($token); } /** * get the authenticated user. * * @return \illuminate\http\jsonresponse */ public function me() { return response()->json(jwtauth::parsetoken()->touser()); } /** * log the user out (invalidate the token). * * @return \illuminate\http\jsonresponse */ public function logout() { jwtauth::parsetoken()->invalidate(); return response()->json(['message' => 'successfully logged out']); } /** * refresh a token. * * @return \illuminate\http\jsonresponse */ public function refresh() { return $this->respondwithtoken(jwtauth::parsetoken()->refresh()); } /** * get the token array structure. * * @param string $token * * @return \illuminate\http\jsonresponse */ protected function respondwithtoken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => jwtauth::factory()->getttl() * 60 ]); }}
注意:attempt 一直返回false,是因为password被加密了,使用bcrypt或者password_hash加密后就可以了
10、验证token获取用户信息
有两种使用方法:
加到 url 中:?token=你的token
加到 header 中,建议用这种,因为在 https 情况下更安全:authorization:bearer 你的token
11、首先使用artisan命令生成一个中间件,我这里命名为refreshtoken.php,创建成功后,需要继承一下jwt的basemiddleware
代码如下:
<?phpnamespace app\http\middleware;use auth;use closure;use tymon\jwtauth\exceptions\jwtexception;use tymon\jwtauth\http\middleware\basemiddleware;use tymon\jwtauth\exceptions\tokenexpiredexception;use symfony\component\httpkernel\exception\unauthorizedhttpexception;// 注意,我们要继承的是 jwt 的 basemiddlewareclass refreshtoken extends basemiddleware{ /** * handle an incoming request. * * @ param \illuminate\http\request $request * @ param \closure $next * * @ throws \symfony\component\httpkernel\exception\unauthorizedhttpexception * * @ return mixed */ public function handle($request, closure $next) { // 检查此次请求中是否带有 token,如果没有则抛出异常。 $this->checkfortoken($request); // 使用 try 包裹,以捕捉 token 过期所抛出的 tokenexpiredexception 异常 try { // 检测用户的登录状态,如果正常则通过 if ($this->auth->parsetoken()->authenticate()) { return $next($request); } throw new unauthorizedhttpexception('jwt-auth', '未登录'); } catch (tokenexpiredexception $exception) { // 此处捕获到了 token 过期所抛出的 tokenexpiredexception 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中 try { // 刷新用户的 token $token = $this->auth->refresh(); // 使用一次性登录以保证此次请求的成功 auth::guard('api')->onceusingid($this->auth->manager()->getpayloadfactory()->buildclaimscollection()->toplainarray()['sub']); } catch (jwtexception $exception) { // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。 throw new unauthorizedhttpexception('jwt-auth', $exception->getmessage()); } } // 在响应头中返回新的 token return $this->setauthenticationheader($next($request), $token); }}
这里主要需要说的就是在token进行刷新后,不但需要将token放在返回头中,最好也将请求头中的token进行置换,因为刷新过后,请求头中的token就已经失效了,如果接口内的业务逻辑使用到了请求头中的token,那么就会产生问题。
这里使用
$request->headers->set('authorization','bearer '.$token);
将token在请求头中刷新。
创建并且写完中间件后,只要将中间件注册,并且在app\exceptions\handler.php内加上一些异常处理就ok了。
12、kernel.php文件中
$routemiddleware 添加中间件配置
'refreshtoken' => \app\http\middleware\refreshtoken::class,
13、添加路由
route::group(['prefix' => 'user'],function($router) { $router->get('userinfo','usercontroller@userinfo')->middleware('refreshtoken');});
在控制器中通过  jwtauth::user();就可以获取用户信息
更多laravel框架技术文章,请访问laravel教程!
以上就是laravel安装jwt-auth及验证(实例)的详细内容。
其它类似信息

推荐信息