1. 安装类库
composer require firebase/php-jwt
2. 登录接口。
引入类库(use Firebase\JWT\JWT; )->查询数据库用户名、密码正确->生成Token并返回
public function login(Request $request)
{
$user_name = $request->get('username','');
$password = $request->get('password','');
$user = Users::where(['username' => $user_name,'password' => $password])->first();
if(!$user)
{
return response()->json('用戶名或密碼錯誤!');
}
unset($user['password']);
//登录成功token
$token = $this->getJWTToken($user);
cache('user-'.$user['id'],$user);
return response()->json(['token' => $token]);
}
public function getJWTToken($value)
{
$time = time();
$payload = [
'iat' => $time,
'nbf' => $time,
'exp' => $time+7200,
'data' => [
'id' => $value['id'],
'username' => $value['user_name']
]
];
$key = env('JWT_SECRET');
$alg = 'HS256';
$token = JWT::encode($payload,$key,$alg);
return $token;
}
配置路由:
Route::post('/login', 'Auth\LoginController@login');
结果如下:
3.创建验证token是否合法的中间件 php artisan make:middleware AuthToken
文件代码如下:
public function handle($request, Closure $next)
{
$alg =
[
"typ" => "JWT", //声明类型为jwt
"alg" => "HS256" //声明签名算法为SHA256
];
$jwt = $request->header('token');
$key = env('JWT_SECRET');
try{
JWT::decode($jwt,$key,$alg);
}
catch (\Exception $e)
{
return response()->json('token无效:'.$e);
}
return $next($request);
}
在kernel.php文件中$routeMiddleware加入中间件
4.创建测试接口
路由配置:
Route::get('/user', 'UsersController@index')->middleware('auth.token');
用登录接口生成的token,写入/user接口的header位置进行测试
如果token不正确,结果如下:具体的返回错误可以查看类库中的JWT.php中decode方法中返回错误,然后自己改写。
海报
0 条评论
176
相关文章
本站已关闭游客评论,请登录或者注册后再评论吧~