前言
# 使用组件
https://github.com/tymondesigns/jwt-auth
# 组件安装
composer require tymon/jwt-auth
# 将配置文件copy到config目录下
# config/jwt.php
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
配置(config/jwt.php)
属性 | 作用 |
---|---|
secret | 签名字符串 类似RSA这种的算法不使用该参数 |
keys.public | 公钥 |
keys.private | 私钥 |
ttl | 令牌生存时效 |
refresh_ttl | 令牌刷新时效,生成后多久之内可以刷新令牌 |
algo | 加密方式 |
# 这里我选择rsa256加密验证方式
algo:RS512
# keys.public | keys.private
可以去 https://cryptotools.net 网站生成
token生成
# 1.用户模型需要实现jwt-auth的接口
User implemnts \Tymon\JWTAuth\Contracts\JWTSubject
getJWTIdentifier() 方法返回用户唯一标识,一般返回主键即可
getJWTCustomClaims() 位json web Token body添加其他属性,一般不需要添加多余的属性,返回 [] 即可
# 2.配置看守guard(config/auth.php)
# 增加了基于jwt驱动的看守
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
# 直接使用看守生成token
$user = User::query()->find(2);
$token = Auth::guard('api')->login($user);
token传递方式
# 第一种放入http的header头中
Authorization: Bearer "token"
# 第二种放入请求中
http://www.baidu.com?token="token"
验证方式
# 第一种在添加路由时指定中间件
Route::get('/', 'Test\IndexController@index')->middleware('auth:api');
# 第二种在控制器中添加使用中间件
$this->middleware('auth:api');
# 最后结果都是将中间件绑定到路由上
# 排除验证当前控制器的指定方法
$this->middleware('auth:api')->except('index');
# 只验证当前控制器的指定方法
$this->middleware('auth:api')->only('index');
# 默认验证不通过,执行会跳到路由名称为login的路由上
# name("名称")
# 下面是给路由添加名称例子
Route::get('/login',"LoginController@login")->name('login');
# 如果不想跳转
# 需要重写App\Http\Middleware\unauthenticated 方法
# 在该方法中抛出自定义异常,在App\Exceptions\Handler\render 处理该异常
App\Http\Middleware\unauthenticated
namespace App\Http\Middleware;
use App\Exceptions\BusinessException;
use App\Http\Controllers\Core\AppCode;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
protected function unauthenticated($request, array $guards)
{
throw new BusinessException(AppCode::notLogin);
}
}
App\Exceptions\Handler\render
namespace App\Http\Middleware;
use App\Exceptions\BusinessException;
use App\Http\Controllers\Core\AppCode;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
return route('login');
}
}
protected function unauthenticated($request, array $guards)
{
throw new BusinessException(AppCode::notLogin);
}
}
token刷新
\auth()->guard('api')->refresh();
获取用户信息
\auth()->guard('api')->user();
存储驱动
# 主动让token失效依赖黑名单,黑名单依赖缓存
# jwt-auth 使用的是缓存的默认驱动
# 修改缓存默认驱动即可 config/cache.php
'default' => env('CACHE_DRIVER', 'redis'),