Download the PHP package ajiho/think-jwt without Composer
On this page you can find all versions of the php package ajiho/think-jwt. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download ajiho/think-jwt
More information about ajiho/think-jwt
Files in ajiho/think-jwt
Package think-jwt
Short Description lcobucci/jwt integration for thinkphp6
License MIT
Homepage https://gitee.com/ajiho/think-jwt
Informations about the package think-jwt
think-jwt
基于lcobucci/jwt封装的一个jwt工具包,在前后端分离时 它非常有用。
安装
composer require ajiho/think-jwt
配置
/config/jwt.php
使用
think-jwt的使用方式非常简单,因为它不管你是如何传递token参数的,你可以选择Header、Cookie、Param,那都是你的自由,think-jwt只纯粹的提供3个核心静态方法( create、parse、logout)和一个辅助静态方法(getRequestToken)
getRequestToken
一般情况都是在请求头中通过Authorization
字段传递token,
所以该方法就是快速获取请求头中Authorization
的token值
注意
如果你是使用apache
服务器的话,需要在tp6项目public/.htaccess
重写文件中添加上一下重写规则,
否则可能接收不到请求头中Authorization
的值。
#Authorization Headers
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
.htaccess
完整内容如下
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
#Authorization Headers
RewriteCond %{HTTP:Authorization} ^(.+)$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>
create
生成token
执行成功返回token字符串
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvYXBpLnh4eC5jb20iLCJhdWQiOiJodHRwczpcL1wvd3d3Lnh4eC5jb20iLCJqdGkiOiIzZjJnNTdhOTJhYSIsImlhdCI6MTY1MTg1MTQ2MywibmJmIjoxNjUxODUxNDYyLCJleHAiOjE2NTE4NTg2NjMsIl90aGlua0p3dCI6IntcImlkXCI6MTAwLFwibmFtZVwiOlwiSmFja1wifSJ9.yVjHKxtZii3YfSwGMfFX_PIuBM5co-xpALx7p-Ld2_A
parse
用于解析token,返回值是一个包含code
,msg
,data
的数组,解析返回不同的状态码和说明,
当然了,这一部分逻辑推荐放中间件中去执行
['code' => xx, 'msg' => 'xx', 'data' => null]
状态码说明
状态码 | 说明 |
---|---|
200 | token解析成功,可以通过data字段得到token中存储的数据(生成token传入的什么类型的数据返回就是什么类型的数据) |
10000 | token已经被注销 |
10001 | token解码失败 |
10002 | 签发人验证失败 |
10003 | 接收人验证失败 |
10004 | token已过期 |
10005 | 编号验证失败 |
10006 | 主题验证失败 |
10007 | 签名密钥验证失败 |
下面是在中间件中验证token的示例代码:
然后你在任意地方只需要依赖注入request请求对象,就能得到登录的用户id
logout
Jwt的token一经签发是它是无法被注销的,所以只能通过服务端来进行判断(结果到这里又变成有状态的了),这里
是通过把要注销的token存储到缓存中,所以配置文件jwt.php
中它有个delete_key
配置就是用来实现注销功能的,默认
缓存的key是delete_token
,如果和你的业务发生冲突,你可以自行更改。
这里的的缓存用的是tp6框架自带的缓存cache
方法
代码示例
此时客户端继续使用已经被注销的token来解析就会提示token已被注销,它过不了中间件的验证
All versions of think-jwt with dependencies
topthink/framework Version ^6.0 || ^8.0
lcobucci/jwt Version ~4.1.5
ext-json Version *