最近项目作API认证,最终技术选型决定使用JWT,项目框架使用的是laravel,laravel使用JWT有比较方便使用的开源包:jwt-auth。 使用composer安装jwt-auth,laravel使用的框架版本为5.0,jwt-auth最新稳定版本为0.5.12。(最新版为1.0.*,需laravel5.4以上)
composer require tymon/jwt-auth 0.5.*
安装完成后,须要在config/app.php中注册相应的服务提供者:
'providers' => [ 'Tymon\JWTAuth\Providers\JWTAuthServiceProvider', ],
而后注册须要用到的对应门面:
'aliases' => [ 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth', 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory', ],
而后发布相应配置文件:此命令会在 config 目录下生成一个 jwt.php 配置文件,你能够在此进行自定义配置。
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
最后生成密钥:此命令会在你的 .env 文件中新增一行 JWT_SECRET=secret
php artisan jwt:generate
生成TOKEN,生成TOKEN有多种方式:下面介绍两种
1、根据模型为基础生成TOKEN:php
根据模型生成TOKEN需在config/auth.php指定使用哪一个模型。
'model' => 'App\Models\Members',
在模型文件Members.php中需添加
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Authenticatable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; class Members extends Model implements AuthenticatableContract { use Authenticatable; ... }
根据模型生成TOKEN
$member = \App\Models\Members::where('id',7)->select('id','username')->first(); $token = \JWTAuth::fromUser($member); echo $token;exit;
2、自定义生成TOKEN:laravel
$customClaims = ['sub' => [ 'id' => '7', 'name' => 'kocor', ]]; $payload = \JWTFactory::make($customClaims); $token = \JWTAuth::encode($payload); echo $token;exit;
解密提取TOKEN信息json
提取TOKEN信息
$user_info = JWTAuth::parseToken()->authenticate()
刷新TOKEN
$newToken = JWTAuth::refresh($_REQUEST['token']);
使用实例
use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; //JWT提取会员信息 try { if (! $user_info = JWTAuth::parseToken()->authenticate()) { return Api::arr(config('statusCode.jwt_user_not_found'), trans('message.jwt_user_not_found').':404'); } //在token有效期内容许刷新 $newToken = JWTAuth::refresh($_REQUEST['token']); return Api::json(config('statusCode.success'), trans('message.success'),$newToken); } catch (TokenExpiredException $e) { try { //在刷新有效期内 $newToken = JWTAuth::refresh($_REQUEST['token']); return Api::json(config('statusCode.success'), trans('message.success'),$newToken); } catch (JWTException $e) { // 过时用户 return Api::json(config('statusCode.jwt_token_expired'), trans('message.jwt_token_expired').$e->getStatusCode()); } //无效的token } catch (TokenInvalidException $e) { return Api::json(config('statusCode.jwt_token_invalid'), trans('message.jwt_token_invalid').$e->getStatusCode()); //token不存在 } catch (JWTException $e) { return Api::json(config('statusCode.jwt_token_absent'), trans('message.jwt_token_absent').$e->getStatusCode()); }
by kocorapp