PHP code example of ajiho / think-jwt
1. Go to this page and download the library: Download ajiho/think-jwt library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
ajiho / think-jwt example snippets
return [
//注销token缓存key
'delete_key' => 'delete_token',
//时区
'timezone' => 'Asia/Shanghai',
//编号
'jti' => '4f1g23a12aa',
//签名密钥
'sign' => 'a4693602cbb7a',
//签发人
'iss' => 'http://example.cn',
//接收人
'aud' => [
'http://example.com',
'http://example.org',
'http://example.top',
],
//主题
'sub' => '100',
//有效期(默认两个小时) 单位:秒
'exp' => 3600 * 2
];
use ajiho\Jwt;
$token = Jwt::create(100);
$token = Jwt::create('php是世界上最好的语言');
$token = Jwt::create(['id'=>100,'name'=>'jack']);
//生成token
$token = Jwt::create(100);// eyJ0eXAiOiJKV1...
/**
* 验证token的中间件
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
// 这里我们直接解析上面生成的token
// $parseResult = Jwt::parse('eyJ0eXAiOiJKV1...');
//您也可以不传递它会默认解析请求头中的HTTP_AUTHORIZATION字段(v2.0.3+)
$parseResult = Jwt::parse();
if ($parseResult['code'] !== 200) {//不等于200等于解析失败
// 您可以在这里笼统的直接返回token解析失败,然后给前端返回一个401
return json(['code' => 401, 'msg' => 'token解析失败', 'data' => []]);
//如果您有特殊需求,可以根据上面的状态码获取具体的错误消息,比如可以判断token是否已经过期等
//...
}
//验证通过,将得到的用户id,放到请求信息中去,方便后续使用
$request->user_id = $parseResult['data'];//100
return $next($request);
}
//获取当前登录用户的信息
public function userInfo(Request $request)
{
$user = User::where('status', 1)
->find($request->user_id);
return json($user);
}
//退出登录
public function logout()
{
//Jwt::logout('eyJ0eXAiOiJKV1...');
//您也可以不传递,它会默认注销请求头中HTTP_AUTHORIZATION传递过来的token(v2.0.3+)
Jwt::logout();
return json(['code' => 200, 'msg' => '用户退出成功', 'data' => []]);
}
/**
* 验证token中间件
*
* @param \think\Request $request
* @param \Closure $next
* @return Response
*/
public function handle($request, \Closure $next)
{
$parseResult = Jwt::parse('eyJ0eXAiOiJKV1...');
if ($parseResult['code'] !== 200) {
dd($parseResult);//['code' => 10000, 'msg' => 'token已经被注销', 'data' => []],因此被注销后的token它是无法继续向下执行的。
return json(['code' => 401, 'msg' => 'token解析失败', 'data' => []]);
}
//验证通过,将得到的用户id,放到请求信息中去,方便后续使用
$request->user_id = $parseResult['data'];//100
return $next($request);
}