本文主要是介绍JWT 之dingo/api,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
JWT (json web token)
dingo/api 以经内置了jwt
基本术语
header (头部)
申明加密算法,JWT最后是通过base64编码
payload (载荷)
过期时间,用户数据 JWT 最后是通过 Base64 编码,可被翻译回原来的样子
signature (签名)
由服务器进行的签名,保证了 token 不被篡改。```{"typ":"JWT","alg":"HS256"}{"iss":"http://larbbs.test","iat":1515733500,"exp":1515737100,"nbf":1515733500,"jti":"c3U4VevxG2ZA1qhT","sub":1,"prv":"23bd5c8949f600adb39e701c400872db7a5976f7"}signature ```
在dingo中使用jwt
- auth.php api配置jwt驱动
- dingo api配置auth项,指向
Dingo\Api\Auth\Provider\JWT
类 - 安装
tymon/jwt-auth
包
jwt载荷术语
Tymon\JWTAuth\Providers\JWTAuthServiceProvide
Tymon\JWTAuth\PayloadFactory
JWTFactory 门面配置
Secret Key - secretToken time to live - ttlRefresh time to live - refresh_ttlHashing algorithm - algoUser model path - userUser identifier - identifierRequired claims - required_claimsBlacklist enabled - blacklist_enabledProvidersUser - providers.userJWT - providers.jwtAuthentication - providers.authStorage - providers.storage
payload 说明
- sub
Subject 保存token的标识,默认值为user的id - iat
Issued At token发行的unix时间戳 - exp
Expiry 过期时间 - nbf
Not Before 最早可被使用的token时间点 - iss
Issuer 默认请求的url地址 - jti
JWT id token的唯一标识,通常由发行时间与sub MD5求值所得
-aud
Audience 接收者参数非必选项
- sub
生成token
// 用户证书(凭证)$credentials = $request->only('email', 'password');$token = JWTAuth::attempt($credentials)// 用户对象$user = User::first();$token = JWTAuth::fromUser($user);// 自定义第二个参数,该参数在解码token时会用到$customClaims = ['foo' => 'bar', 'baz' => 'bob'];JWTAuth::attempt($credentials, $customClaims);// orJWTAuth::fromUser($user, $customClaims);// 自定义token$customClaims = ['foo' => 'bar', 'baz' => 'bob'];$payload = JWTFactory::make($customClaims);$token = JWTAuth::encode($payload);// 支持链式调用$payload = JWTFactory::sub(123)->aud('foo')->foo(['bar' => 'baz'])->make();$token = JWTAuth::encode($payload);
认证(验证)authentication
header头内传递token
```AuthorizationAuthorization: Bearer {yourtokenhere}```*warning 对于apache而言非base64编码内容会被丢弃,修复如下*```fixRewriteEngine OnRewriteCond %{HTTP:Authorization} ^(.*)RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]``` 2.
查询字符串传递
```http://api.mysite.com/me?token={yourtokenhere}// 从请求中解析tokenJWTAuth::setToken('foo.bar.baz');$token = JWTAuth::getToken();$user = JWTAuth::parseToken()->authenticate(); ``` 3.
事件
```// fired when the token could not be found in the requestEvent::listen('tymon.jwt.absent');// fired when the token has expiredEvent::listen('tymon.jwt.expired');// fired when the token is found to be invalidEvent::listen('tymon.jwt.invalid');// fired if the user could not be found (shouldn't really happen)Event::listen('tymon.jwt.user_not_found');// fired when the token is valid (User is passed along with event)Event::listen('tymon.jwt.valid');```
中间件
- GetUserFromToken 检查header和query字符串,解码,同样事件会被触发- RefreshToken使旧的token无效,并返回下一次响应,仅对当一请求有效- 注册```protected $routeMiddleware = ['jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken','jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',];```
这篇关于JWT 之dingo/api的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!