开始安装jwt
(本次安装不建议直接在项目中安装及使用)
1.composer 安装jwt
composer require tymon/jwt-auth 1.0.0-rc.1
2.在config 文件夹的app.php 中注册服务提供者
'providers' => [Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]'aliases' => ['JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
]
3.生成配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
4.生成jwt 密钥
php artisan jwt:secret
然后会在我们的 .env 文件中生成jwt密钥
5.在auth.php 文件中 配置 auth guard 让api的driver使用jwt
'guards' => ['web' => ['driver' => 'session','provider' => 'users',],'api' => ['driver' => 'jwt',//更改此处为jwt'provider' => 'users',],],
6.更改 User model使其支持 jwt-auth
<?phpnamespace App;use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;class User extends Authenticatable implements JWTSubject
{use Notifiable;protected $table = 'users';/*** Get the identifier that will be stored in the subject claim of the JWT.** @return mixed*/public function getJWTIdentifier(){return $this->getKey();}/*** Return a key value array, containing any custom claims to be added to the JWT.** @return array*/public function getJWTCustomClaims(){return [];}
7.配置 中间件
在 Middleware 文件夹下新建 ApiAuth.php 中间件文件
<?phpnamespace App\Http\Middleware;use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;class ApiAuth
{/*** Handle an incoming request.** @param \Illuminate\Http\Request $request* @param \Closure $next* @return mixed*/public function handle($request, Closure $next){try {if (! $user = JWTAuth::parseToken()->authenticate()) { //获取到用户数据,并赋值给$userreturn response()->json(['errcode' => 1004,'errmsg' => '无此用户'], 404);}return $next($request);} catch (TokenExpiredException $e) {return response()->json(['errcode' => 1003,'errmsg' => 'token 过期' , //token已过期]);} catch (TokenInvalidException $e) {return response()->json(['errcode' => 1002,'errmsg' => 'token 无效', //token无效]);} catch (JWTException $e) {return response()->json(['errcode' => 1001,'errmsg' => '缺少token' , //token为空]);}}
}
注册中间件 在 Kernel.php 中注册中间件 并设置别名
protected $routeMiddleware = ['api.auth' => \App\Http\Middleware\ApiAuth::class,];
到此你的jwt就算安装配置完成了
**基本使用**
1.新建AuthCtorller.php 控制器
php artisan make:controller AuthController
2.编辑 测试控制器
<?phpnamespace App\Http\Controllers;use App\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Hash;class AuthController extends Controller
{/*** jwt 测试*///登录public function login(Request $request){$username = $request->get('username');$password = $request->get('password');$user_mes = User::where('username','=',$username)->first();if (!$user_mes || !Hash::check($password, $user_mes->password)) {return "账号或密码错误";}$token=JWTAuth::fromUser($user_mes);//生成tokenif (!$token) {return "登录失败,请重试";}return response()->json(['token'=>$token]);}//获取用户信息public function home(){$user=JWTAuth::parseToken()->touser();//获取用户信息return $user;}//退出public function logout(){JWTAuth::parseToken()->invalidate();//退出return '退出成功';}}
3.编辑路由
<?php
Route::post('/login','AuthController@login');//登录
Route::group(['middleware' => 'api.auth'], function () {Route::post('/home','AuthController@home');//获取用户信息Route::post('/logout','AuthController@logout');//退出});
配置JWT过期时间
config/jwt.php
token过期刷新
public function refresh(){try {// 获取旧token$old_token = JWTAuth::getToken();// 刷新token$token = JWTAuth::refresh($old_token);// 使老的token无效JWTAuth::invalidate($old_token);return response()->json(['token' => $token,]);} catch (JWTException $JWTException) {// 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。throw new UnauthorizedHttpException('jwt-auth', $JWTException->getMessage());}}