├── .gitignore ├── .styleci.yml ├── LICENSE ├── README.md ├── SUPPORT.md ├── composer.json ├── config └── config.php └── src ├── Blacklist.php ├── JWT.php ├── JWTAuth.php ├── Manager.php ├── Payload.php ├── Service.php ├── Token.php ├── claim ├── Audience.php ├── Claim.php ├── Customer.php ├── Expiration.php ├── Factory.php ├── IssuedAt.php ├── Issuer.php ├── JwtId.php ├── NotBefore.php └── Subject.php ├── command └── SecretCommand.php ├── contract ├── Parser.php └── Storage.php ├── exception ├── BadMethodCallException.php ├── JWTException.php ├── TokenBlacklistException.php ├── TokenBlacklistGracePeriodException.php ├── TokenExpiredException.php ├── TokenInvalidException.php └── UserNotDefinedException.php ├── facade └── JWTAuth.php ├── helper.php ├── middleware ├── BaseMiddleware.php ├── InjectJwt.php ├── JWTAuth.php └── JWTAuthAndRefresh.php ├── parser ├── AuthHeader.php ├── Cookie.php ├── KeyTrait.php ├── Param.php └── Parser.php └── provider ├── JWT.php ├── JWT ├── Lcobucci.php └── Provider.php └── storage ├── Tp5.php └── Tp6.php /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | version: 8.1 2 | preset: psr2 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Thans 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |

JWT-AUTH

3 |

thinkphp的jwt(JSON Web Token)身份验证包。支持Header、Cookie、Param等多种传参方式。包含:验证、验证并且自动刷新等多种中间件。

4 | 5 | [thinkphp6.0的demo下载](https://gitee.com/thans/jwt-auth/attach_files/306748/download) 6 | 7 | ## 支持Swoole 8 | 9 | ## 环境要求 10 | 11 | 1. php ~8.1.0 || ~8.2.0 12 | 2. thinkphp ^5.1.10 || ^6.0.0 || ^8.0.0 13 | 14 | > 2.x 要求 PHP 8.1 以上,8.0及以下请使用1.x 15 | 16 | ## 说明 17 | > 目前支持如下三大类型加密方式:RSA,HASH,DSA。再各分256、384、512位。 18 | 默认是HS256,即hash 256位加密。 19 | 20 | >需要修改加密方式,请修改参数:ALGO,参数选项: 21 | * HS256 22 | > 备注:hash 256位 23 | * HS384 24 | > 备注:hash 384位 25 | * HS512 26 | > 备注:hash 512位 27 | * RS256 28 | > 备注:rsa 256位 29 | * RS384 30 | > 备注:rsa 384位 31 | * RS512 32 | > 备注:rsa 512位 33 | * ES256 34 | > 备注:dsa 256位 35 | * ES384 36 | > 备注:dsa 384位 37 | * ES512 38 | > 备注:dsa 512位 39 | 40 | > 重要:RSA和DSA 都是非对称加密方式,除了修改参数ALGO外,需要配置:PUBLIC_KEY、PRIVATE_KEY两个参数, 41 | > 这两个参数**只支持**密钥文件路径。如果密钥设置了密码,请配置好参数:PASSWORD 42 | 43 | ## 安装 44 | 45 | 第一步: 46 | 47 | ```shell 48 | $ composer require thans/tp-jwt-auth 49 | ``` 50 | 51 | 52 | 第二步: 53 | 54 | ```shell 55 | $ php think jwt:create 56 | ``` 57 | 此举将生成jwt.php和.env配置文件。不推荐直接修改jwt.php 58 | 同时,env中会随机生成secret。请不要随意更新secret,也请保障secret安全。 59 | 60 | 61 | ## 使用方式 62 | 63 | 对于需要验证的路由或者模块添加中间件: 64 | ```php 65 | thans\jwt\middleware\JWTAuth::class, 66 | ``` 67 | 68 | 示例: 69 | 70 | ```php 71 | use thans\jwt\facade\JWTAuth; 72 | 73 | $token = JWTAuth::builder(['uid' => 1]);//参数为用户认证的信息,请自行添加 74 | 75 | JWTAuth::auth();//token验证 76 | 77 | JWTAuth::refresh();//刷新token,会将旧token加入黑名单 78 | 79 | $tokenStr = JWTAuth::token()->get(); //可以获取请求中的完整token字符串 80 | 81 | $payload = JWTAuth::auth(); //可验证token, 并获取token中的payload部分 82 | $uid = $payload['uid']; //可以继而获取payload里自定义的字段,比如uid 83 | 84 | ``` 85 | token刷新说明: 86 | 87 | > token默认有效期为60秒,如果需要修改请修改env文件。 88 | > refresh_ttl为刷新token有效期参数,单位为分钟。默认有效期14天。 89 | > token过期后,旧token将会被加入黑名单。 90 | > 如果需要自动刷新,请使用中间件 thans\jwt\middleware\JWTAuthAndRefresh::class, 91 | > 自动刷新后会通过header返回,请保存好。(注意,此中间件过期后第一次访问正常,第二次进入黑名单。) 92 | 93 | 94 | token传参方式如下: 95 | 96 | > 可通过jwt.php配置文件内token_mode参数来调整参数接收方式及优先级 97 | > token_mode默认值为['header', 'cookie', 'param']; 98 | 99 | > 在某些前后端分离的情况下可选择取消cookie接收方式来避免token冲突 100 | 101 | - 将token加入到url中作为参数。键名为token 102 | - 将token加入到cookie。键名为token 103 | - 将token加入header,如下:Authorization:bearer token值 104 | - 以上三种方式,任选其一即可。推荐加入header中。 105 | 106 | #### 其他操作 107 | 1. 拉黑Token JWTAuth::invalidate($token); 108 | 2. 查询Token是否黑名单 JWTAuth::validate($token); 109 | 110 | #### 常见问题 111 | - 使用RSA256方式的时候,请使用文本形式。如下: 112 | 113 | ## 联系&打赏 114 | 115 | [打赏名单](SUPPORT.md) 116 | 117 | ![image](https://img.thans.cn/wechat.jpg) 118 | 119 | ## 参考与借鉴 120 | 121 | https://github.com/tymondesigns/jwt-auth 122 | 123 | ## 感谢 124 | 125 | - jwt-auth 126 | - php 127 | - lcobucci/jwt 128 | - thinkphp 129 | 130 | ## 下一步 131 | 132 | - 支持动态配置 133 | 134 | ## License 135 | 136 | MIT 137 | -------------------------------------------------------------------------------- /SUPPORT.md: -------------------------------------------------------------------------------- 1 | **打赏名单** 2 | 3 | 4 | 名字 | 金额 | 留言/事由 5 | ---|---|--- 6 | kmapay | 50.00 | 问题咨询 7 | King超 | 28.88 | 赞助打赏 8 | Hugo | 18.00 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "thans/tp-jwt-auth", 3 | "description": "thinkphp jwt auth composer", 4 | "type": "library", 5 | "require": { 6 | "php": ">=8.0", 7 | "lcobucci/jwt": "^4.3", 8 | "topthink/framework": ">=6.0" 9 | }, 10 | "license": "MIT", 11 | "authors": [ 12 | { 13 | "name": "Thans", 14 | "email": "ntbperst@outlook.com" 15 | } 16 | ], 17 | "autoload": { 18 | "psr-4": { 19 | "thans\\jwt\\": "src" 20 | }, 21 | "files": [ 22 | "src/helper.php" 23 | ] 24 | }, 25 | "extra": { 26 | "think": { 27 | "services": [ 28 | "thans\\jwt\\Service" 29 | ], 30 | "config": { 31 | "jwt": "config/config.php" 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | env('JWT_SECRET'), 6 | //Asymmetric key 7 | 'public_key' => env('JWT_PUBLIC_KEY'), 8 | 'private_key' => env('JWT_PRIVATE_KEY'), 9 | 'password' => env('JWT_PASSWORD'), 10 | //JWT time to live 11 | 'ttl' => env('JWT_TTL', 60), 12 | //Refresh time to live 13 | 'refresh_ttl' => env('JWT_REFRESH_TTL', 20160), 14 | //JWT hashing algorithm 15 | 'algo' => env('JWT_ALGO', 'HS256'), 16 | //token获取方式,数组靠前值优先 17 | 'token_mode' => ['header', 'cookie', 'param'], 18 | //黑名单后有效期 19 | 'blacklist_grace_period' => env('BLACKLIST_GRACE_PERIOD', 10), 20 | 'blacklist_storage' => thans\jwt\provider\storage\Tp5::class, 21 | ]; 22 | -------------------------------------------------------------------------------- /src/Blacklist.php: -------------------------------------------------------------------------------- 1 | storage = $storage; 16 | } 17 | 18 | public function add($payload) 19 | { 20 | $this->set($this->getKey($payload), $this->getGraceTimestamp(), $this->getSecondsUntilExpired($payload)); 21 | 22 | return $this; 23 | } 24 | 25 | public function has($payload) 26 | { 27 | return $this->get($this->getKey($payload)) ? true : false; 28 | } 29 | 30 | public function hasGracePeriod($payload) 31 | { 32 | $val = (int) $this->get($this->getKey($payload)); 33 | 34 | return $val && $val >= time(); 35 | } 36 | 37 | protected function getKey($payload) 38 | { 39 | return $payload['jti']; 40 | } 41 | 42 | public function set($key, $val, $time = 0) 43 | { 44 | $this->storage->set($key, $val, $time); 45 | 46 | return $this; 47 | } 48 | 49 | public function get($key) 50 | { 51 | return $this->storage->get($key); 52 | } 53 | 54 | public function remove($key) 55 | { 56 | return $this->storage->delete($key); 57 | } 58 | 59 | public function getRefreshTTL() 60 | { 61 | return $this->refreshTTL; 62 | } 63 | 64 | public function setRefreshTTL($ttl) 65 | { 66 | $this->refreshTTL = (int) $ttl; 67 | 68 | return $this; 69 | } 70 | 71 | public function getGracePeriod() 72 | { 73 | return $this->gracePeriod; 74 | } 75 | 76 | public function setGracePeriod($gracePeriod) 77 | { 78 | $this->gracePeriod = (int) $gracePeriod; 79 | 80 | return $this; 81 | } 82 | 83 | protected function getSecondsUntilExpired($payload) 84 | { 85 | $iat = $payload['iat']; 86 | return $iat + $this->getRefreshTTL() * 60 - time(); 87 | } 88 | 89 | protected function getGraceTimestamp() 90 | { 91 | return time() + $this->gracePeriod; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/JWT.php: -------------------------------------------------------------------------------- 1 | parser; 18 | } 19 | 20 | public function __construct(Manager $manager, Parser $parser) 21 | { 22 | $this->manager = $manager; 23 | $this->parser = $parser; 24 | } 25 | 26 | public function createToken($customerClaim = []) 27 | { 28 | return $this->manager->encode($customerClaim)->get(); 29 | } 30 | 31 | public function parseToken() 32 | { 33 | if (!$token = $this->parser->parseToken()) { 34 | throw new JWTException('No token is this request.'); 35 | } 36 | $this->setToken($token); 37 | 38 | return $this; 39 | } 40 | 41 | public function getToken() 42 | { 43 | if ($this->token === null) { 44 | try { 45 | $this->parseToken(); 46 | } catch (JWTException $e) { 47 | $this->token = null; 48 | } 49 | } 50 | 51 | return $this->token; 52 | } 53 | 54 | public function setToken($token) 55 | { 56 | $this->token = $token instanceof Token ? $token : new Token($token); 57 | 58 | return $this; 59 | } 60 | 61 | public function requireToken() 62 | { 63 | $this->getToken(); 64 | 65 | if (!$this->token) { 66 | throw new JWTException('Must have token'); 67 | } 68 | } 69 | 70 | /** 71 | * 获取Payload 72 | * @return mixed 73 | * @throws JWTException 74 | * @throws exception\TokenBlacklistException 75 | */ 76 | public function getPayload() 77 | { 78 | $this->requireToken(); 79 | 80 | return $this->manager->decode($this->token); 81 | } 82 | 83 | /** 84 | * 刷新Token 85 | * @return mixed 86 | * @throws JWTException 87 | */ 88 | public function refresh() 89 | { 90 | $this->parseToken(); 91 | 92 | return $this->manager->refresh($this->token)->get(); 93 | } 94 | 95 | 96 | 97 | public function __call($method, $parameters) 98 | { 99 | if (method_exists($this->manager, $method)) { 100 | return call_user_func_array([$this->manager, $method], $parameters); 101 | } 102 | 103 | throw new BadMethodCallException("Method [$method] does not exist."); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/JWTAuth.php: -------------------------------------------------------------------------------- 1 | manager->setValidate($validate); 21 | return (array)$this->getPayload(); 22 | } 23 | 24 | /** 25 | * Token构建 26 | * 27 | * @param array $user 28 | * 29 | * @return mixed 30 | */ 31 | public function builder(array $user = []) 32 | { 33 | return $this->createToken($user); 34 | } 35 | 36 | /** 37 | * 获取Token 38 | * 39 | * @return mixed 40 | */ 41 | public function token() 42 | { 43 | return $this->getToken(); 44 | } 45 | 46 | /** 47 | * 添加Token至黑名单 48 | * 49 | * @param $token 50 | * 51 | * @return Blacklist 52 | * @throws exception\TokenBlacklistException 53 | */ 54 | public function invalidate($token) 55 | { 56 | if ($token instanceof Token) { 57 | return $this->manager->invalidate($token); 58 | } 59 | 60 | return $this->manager->invalidate(new Token($token)); 61 | } 62 | 63 | /** 64 | * 是否在黑名单 65 | * 66 | * @param $token 67 | * 68 | * @return bool 69 | */ 70 | public function validate($token) 71 | { 72 | if ($token instanceof Token) { 73 | return $this->manager->validate($this->manager->provider->decode($token->get())); 74 | } 75 | 76 | return $this->manager->validate($this->manager->provider->decode($token)); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Manager.php: -------------------------------------------------------------------------------- 1 | blacklist = $blacklist; 27 | $this->payload = $payload; 28 | $this->provider = $provider; 29 | } 30 | 31 | /** 32 | * Token编码 33 | * 34 | * @param $customerClaim 35 | * 36 | * @return Token 37 | */ 38 | public function encode($customerClaim = []) 39 | { 40 | $payload = $this->payload->customer($customerClaim); 41 | $token = $this->provider->encode($payload->get()); 42 | 43 | return new Token($token); 44 | } 45 | 46 | /** 47 | * 解析Token 48 | * 49 | * @param Token $token 50 | * 51 | * @return mixed 52 | * @throws TokenBlacklistException 53 | */ 54 | public function decode(Token $token) 55 | { 56 | $payload = $this->provider->decode($token->get()); 57 | if ($this->validate) { 58 | //blacklist grace period verify 59 | if ($this->validateGracePeriod($payload)) { 60 | throw new TokenBlacklistGracePeriodException('The token is in blacklist grace period list.'); 61 | } 62 | 63 | //blacklist verify 64 | if ($this->validate($payload)) { 65 | throw new TokenBlacklistException('The token is in blacklist.'); 66 | } 67 | } 68 | 69 | $this->payload->customer($payload)->check($this->refresh); 70 | 71 | return $payload; 72 | } 73 | 74 | /** 75 | * 刷新Token 76 | * 77 | * @param Token $token 78 | * 79 | * @return Token 80 | * @throws TokenBlacklistException 81 | */ 82 | public function refresh(Token $token) 83 | { 84 | $this->setRefresh(); 85 | 86 | $payload = $this->decode($token); 87 | 88 | $this->invalidate($token); 89 | 90 | $this->payload->customer($payload) 91 | ->check(true); 92 | 93 | return $this->encode($payload); 94 | } 95 | 96 | /** 97 | * 注销Token,使之无效 98 | * 99 | * @param Token $token 100 | * 101 | * @return Blacklist 102 | * @throws TokenBlacklistException 103 | */ 104 | public function invalidate(Token $token) 105 | { 106 | return $this->blacklist->add($this->provider->decode($token->get())); 107 | } 108 | 109 | /** 110 | * 验证是否在黑名单 111 | * 112 | * @param $payload 113 | * 114 | * @return bool 115 | */ 116 | public function validate($payload) 117 | { 118 | return $this->blacklist->has($payload); 119 | } 120 | 121 | public function validateGracePeriod($payload) 122 | { 123 | return $this->blacklist->hasGracePeriod($payload); 124 | } 125 | 126 | public function setRefresh($refresh = true) 127 | { 128 | $this->refresh = true; 129 | 130 | return $this; 131 | } 132 | 133 | public function setValidate($validate = true) 134 | { 135 | $this->validate = $validate; 136 | $this->refresh = !$validate ? true : $this->refresh; 137 | 138 | return $this; 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/Payload.php: -------------------------------------------------------------------------------- 1 | Audience::class, 22 | 'exp' => Expiration::class, 23 | 'iat' => IssuedAt::class, 24 | 'iss' => Issuer::class, 25 | 'jti' => JwtId::class, 26 | 'nbf' => NotBefore::class, 27 | 'sub' => Subject::class, 28 | ]; 29 | 30 | protected $claims; 31 | 32 | public function __construct(Factory $factory) 33 | { 34 | $this->factory = $factory; 35 | } 36 | 37 | public function customer(array $claim = []) 38 | { 39 | foreach ($claim as $key => $value) { 40 | $this->factory->customer( 41 | $key, 42 | is_object($claim) && method_exists($claim, 'getValue') ? $value->getValue() : $value 43 | ); 44 | } 45 | 46 | return $this; 47 | } 48 | 49 | public function get() 50 | { 51 | $claim = $this->factory->builder()->getClaims(); 52 | 53 | return $claim; 54 | } 55 | 56 | public function check($refresh = false) 57 | { 58 | $this->factory->validate($refresh); 59 | 60 | return $this; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Service.php: -------------------------------------------------------------------------------- 1 | commands(SecretCommand::class); 15 | $this->app->middleware->add(InjectJwt::class); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Token.php: -------------------------------------------------------------------------------- 1 | value = $value; 13 | } 14 | 15 | public function get() 16 | { 17 | return $this->value; 18 | } 19 | 20 | public function __toString() 21 | { 22 | return $this->get(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/claim/Audience.php: -------------------------------------------------------------------------------- 1 | setValue($value); 14 | } 15 | 16 | public function setValue($value) 17 | { 18 | $this->value = $value; 19 | 20 | return $this; 21 | } 22 | 23 | public function getValue() 24 | { 25 | return $this->value; 26 | } 27 | 28 | public function setName($name) 29 | { 30 | $this->name = $name; 31 | 32 | return $this; 33 | } 34 | 35 | public function getName() 36 | { 37 | return $this->name; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/claim/Customer.php: -------------------------------------------------------------------------------- 1 | setName($name); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/claim/Expiration.php: -------------------------------------------------------------------------------- 1 | = (int)$this->getValue()) { 15 | throw new TokenExpiredException('The token is expired.'); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/claim/Factory.php: -------------------------------------------------------------------------------- 1 | Audience::class, 15 | 'exp' => Expiration::class, 16 | 'iat' => IssuedAt::class, 17 | 'iss' => Issuer::class, 18 | 'jti' => JwtId::class, 19 | 'nbf' => NotBefore::class, 20 | 'sub' => Subject::class, 21 | ]; 22 | 23 | protected $ttl; 24 | protected $claim = []; 25 | protected $refreshTtl; 26 | 27 | public function __construct(Request $request, $ttl, $refreshTtl) 28 | { 29 | $this->request = $request; 30 | $this->ttl = $ttl; 31 | $this->refreshTtl = $refreshTtl; 32 | } 33 | 34 | public function customer($key, $value) 35 | { 36 | $this->claim[$key] = isset($this->classMap[$key]) 37 | ? new $this->classMap[$key]($value) 38 | : new Customer($key, $value); 39 | 40 | return $this; 41 | } 42 | 43 | public function builder() 44 | { 45 | foreach ($this->classMap as $key => $class) { 46 | $claim[$key] = new $class(method_exists($this, $key) 47 | ? $this->$key() : ''); 48 | } 49 | $this->claim = array_merge($this->claim, $claim); 50 | 51 | return $this; 52 | } 53 | 54 | public function validate($refresh = false) 55 | { 56 | foreach ($this->claim as $key => $claim) { 57 | if (! $refresh && method_exists($claim, 'validatePayload')) { 58 | $claim->validatePayload(); 59 | } 60 | if ($refresh && method_exists($claim, 'validateRefresh')) { 61 | $claim->validateRefresh($this->refreshTtl); 62 | } 63 | } 64 | } 65 | 66 | public function getClaims() 67 | { 68 | return $this->claim; 69 | } 70 | 71 | public function aud() 72 | { 73 | return $this->request->url(); 74 | } 75 | 76 | public function exp() 77 | { 78 | return time() + $this->ttl; 79 | } 80 | 81 | public function iat() 82 | { 83 | return time(); 84 | } 85 | 86 | public function iss() 87 | { 88 | return $this->request->url(); 89 | } 90 | 91 | public function jti() 92 | { 93 | return md5(uniqid().time().rand(100000, 9999999)); 94 | } 95 | 96 | public function nbf() 97 | { 98 | return time(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/claim/IssuedAt.php: -------------------------------------------------------------------------------- 1 | getValue()) { 15 | throw new TokenExpiredException('Issued At (iat) timestamp cannot be in the future.'); 16 | } 17 | } 18 | 19 | public function validateRefresh($refreshTtl) 20 | { 21 | if (time() >= (int)$this->getValue() + $refreshTtl * 60) { 22 | throw new TokenExpiredException('Token has expired and can no longer be refreshed.'); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/claim/Issuer.php: -------------------------------------------------------------------------------- 1 | setName('jwt:create') 15 | ->setDescription('create jwt secret and create config file'); 16 | } 17 | 18 | public function execute(Input $input, Output $output) 19 | { 20 | $key = md5(uniqid().time().rand(0, 60)); 21 | $path = app()->getAppPath().'..'.DIRECTORY_SEPARATOR.'.env'; 22 | if (file_exists($path) 23 | && strpos(file_get_contents($path), '[JWT]') 24 | ) { 25 | $output->writeln('JWT_SECRET is exists'); 26 | } else { 27 | file_put_contents( 28 | $path, 29 | PHP_EOL."[JWT]".PHP_EOL."SECRET=$key".PHP_EOL, 30 | FILE_APPEND 31 | ); 32 | $output->writeln('JWT_SECRET has created'); 33 | } 34 | $this->createConfig($output); 35 | } 36 | 37 | public function createConfig($output) 38 | { 39 | $configFilePath = app()->getAppPath().'..'.DIRECTORY_SEPARATOR.'config' 40 | .DIRECTORY_SEPARATOR.'jwt.php'; 41 | 42 | if (!is_file($configFilePath)) { 43 | $res = copy(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'..' 44 | .DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR 45 | .'config.php', $configFilePath); 46 | 47 | if ($res) { 48 | $output->writeln('Create config file success:'.$configFilePath); 49 | } else { 50 | $output->writeln('Create config file error'); 51 | return; 52 | } 53 | } 54 | 55 | if (strpos(\think\App::VERSION, '5.') !== 0) { 56 | $config = file_get_contents($configFilePath); 57 | $config = str_replace('Tp5', 'Tp6', $config); 58 | file_put_contents($configFilePath, $config); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/contract/Parser.php: -------------------------------------------------------------------------------- 1 | init(); 13 | } 14 | -------------------------------------------------------------------------------- /src/middleware/BaseMiddleware.php: -------------------------------------------------------------------------------- 1 | auth = $auth; 17 | } 18 | 19 | protected function setAuthentication($response, $token = null) 20 | { 21 | $token = $token ?: $this->auth->refresh(); 22 | $this->auth->setToken($token); 23 | 24 | if (in_array('cookie', Config::get('jwt.token_mode'))) { 25 | Cookie::set('token', $token); 26 | } 27 | 28 | if (in_array('header', Config::get('jwt.token_mode'))) { 29 | $response = $response->header(['Authorization' => 'Bearer '.$token]); 30 | } 31 | 32 | return $response; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/middleware/InjectJwt.php: -------------------------------------------------------------------------------- 1 | init(); 14 | $response = $next($request); 15 | return $response; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/middleware/JWTAuth.php: -------------------------------------------------------------------------------- 1 | auth->auth(); 11 | 12 | return $next($request); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/middleware/JWTAuthAndRefresh.php: -------------------------------------------------------------------------------- 1 | isOptions()) { 15 | return response(); 16 | } 17 | 18 | // 验证token 19 | try { 20 | $this->auth->auth(); 21 | } catch (TokenExpiredException $e) { // 捕获token过期 22 | // 尝试刷新token 23 | try { 24 | $this->auth->setRefresh(); 25 | $token = $this->auth->refresh(); 26 | 27 | // $payload = $this->auth->auth(false); 28 | // $request->uid = $payload['uid']; 29 | 30 | $response = $next($request); 31 | return $this->setAuthentication($response, $token); 32 | } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期 33 | // $payload = $this->auth->auth(false); 34 | // $request->uid = $payload['uid']; 35 | 36 | return $next($request); 37 | } 38 | } catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期 39 | // $payload = $this->auth->auth(false); 40 | // $request->uid = $payload['uid']; 41 | } 42 | 43 | return $next($request); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/parser/AuthHeader.php: -------------------------------------------------------------------------------- 1 | header($this->header); 18 | if ($header 19 | && preg_match('/'.$this->prefix.'\s*(\S+)\b/i', $header, $matches) 20 | ) { 21 | return $matches[1]; 22 | } 23 | } 24 | 25 | public function setHeaderName($name) 26 | { 27 | $this->header = $name; 28 | 29 | return $this; 30 | } 31 | 32 | public function setHeaderPrefix($prefix) 33 | { 34 | $this->prefix = $prefix; 35 | 36 | return $this; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/parser/Cookie.php: -------------------------------------------------------------------------------- 1 | key); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/parser/KeyTrait.php: -------------------------------------------------------------------------------- 1 | key = $key; 13 | 14 | return $this; 15 | } 16 | 17 | public function getKey() 18 | { 19 | return $this->key; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/parser/Param.php: -------------------------------------------------------------------------------- 1 | param($this->key); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/parser/Parser.php: -------------------------------------------------------------------------------- 1 | request = $request; 17 | $this->chain = $chain; 18 | } 19 | 20 | public function setRequest(Request $request) 21 | { 22 | $this->request = $request; 23 | 24 | return $this; 25 | } 26 | 27 | public function setChain(array $chain) 28 | { 29 | $this->chain = $chain; 30 | 31 | return $this; 32 | } 33 | 34 | public function getChain() 35 | { 36 | return $this->chain; 37 | } 38 | 39 | public function parseToken() 40 | { 41 | foreach ($this->chain as $parser) { 42 | if ($response = $parser->parse($this->request)) { 43 | return $response; 44 | } 45 | } 46 | } 47 | 48 | public function hasToken() 49 | { 50 | return $this->parseToken() !== null; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/provider/JWT.php: -------------------------------------------------------------------------------- 1 | request = $request; 24 | $config = require __DIR__ . '/../../config/config.php'; 25 | if (strpos(App::VERSION, '5.') !== 0) { 26 | $this->config = array_merge($config, Config::get('jwt') ?? []); 27 | } else { 28 | $this->config = array_merge($config, Config::get('jwt.') ?? []); 29 | } 30 | } 31 | 32 | protected function registerBlacklist() 33 | { 34 | Container::getInstance()->make('thans\jwt\Blacklist', [ 35 | new $this->config['blacklist_storage'], 36 | ])->setRefreshTTL($this->config['refresh_ttl'])->setGracePeriod($this->config['blacklist_grace_period']); 37 | } 38 | 39 | 40 | protected function registerProvider() 41 | { 42 | //builder asymmetric keys 43 | $keys = $this->config['secret'] 44 | ? $this->config['secret'] 45 | : [ 46 | 'public' => $this->config['public_key'], 47 | 'private' => $this->config['private_key'], 48 | 'password' => $this->config['password'], 49 | ]; 50 | Container::getInstance()->make('thans\jwt\provider\JWT\Lcobucci', [ 51 | $this->config['algo'], 52 | $keys, 53 | ]); 54 | } 55 | 56 | protected function registerFactory() 57 | { 58 | Container::getInstance()->make('thans\jwt\claim\Factory', [ 59 | new Request(), 60 | $this->config['ttl'], 61 | $this->config['refresh_ttl'], 62 | ]); 63 | } 64 | 65 | protected function registerPayload() 66 | { 67 | Container::getInstance()->make('thans\jwt\Payload', [ 68 | Container::getInstance()->make('thans\jwt\claim\Factory'), 69 | ]); 70 | } 71 | 72 | protected function registerManager() 73 | { 74 | Container::getInstance()->make('thans\jwt\Manager', [ 75 | Container::getInstance()->make('thans\jwt\Blacklist'), 76 | Container::getInstance()->make('thans\jwt\Payload'), 77 | Container::getInstance()->make('thans\jwt\provider\JWT\Lcobucci'), 78 | ]); 79 | } 80 | 81 | protected function registerJWTAuth() 82 | { 83 | $chains = [ 84 | 'header' => new AuthHeader(), 85 | 'cookie' => new Cookie(), 86 | 'param' => new Param() 87 | ]; 88 | 89 | $mode = $this->config['token_mode']; 90 | $setChain = []; 91 | 92 | foreach ($mode as $key => $chain) { 93 | if (isset($chains[$chain])) { 94 | $setChain[$key] = $chains[$chain]; 95 | } 96 | } 97 | 98 | JWTAuth::parser()->setRequest($this->request)->setChain($setChain); 99 | } 100 | 101 | public function init() 102 | { 103 | $this->registerBlacklist(); 104 | $this->registerProvider(); 105 | $this->registerFactory(); 106 | $this->registerPayload(); 107 | $this->registerManager(); 108 | $this->registerJWTAuth(); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/provider/JWT/Lcobucci.php: -------------------------------------------------------------------------------- 1 | HS256::class, 37 | 'HS384' => HS384::class, 38 | 'HS512' => HS512::class, 39 | 'RS256' => RS256::class, 40 | 'RS384' => RS384::class, 41 | 'RS512' => RS512::class, 42 | 'ES256' => ES256::class, 43 | 'ES384' => ES384::class, 44 | 'ES512' => ES512::class, 45 | ]; 46 | 47 | protected $configuration; 48 | 49 | public function __construct($algo, $keys) 50 | { 51 | $this->algo = $algo; 52 | $this->signer = $this->getSign(); 53 | $this->keys = $keys; 54 | $this->configuration = $this->buildConfiguration(); 55 | } 56 | 57 | 58 | public function encode(array $payload) 59 | { 60 | $builder = $this->getBuilderFromClaims($payload); 61 | try { 62 | return $builder->getToken($this->configuration->signer(), $this->configuration->signingKey()) 63 | ->toString(); 64 | } catch (Exception $e) { 65 | throw new JWTException( 66 | 'Could not create token :' . $e->getMessage(), 67 | $e->getCode(), 68 | $e 69 | ); 70 | } 71 | return (string) $builder->getToken(); 72 | } 73 | 74 | public function decode($token) 75 | { 76 | try { 77 | $token = $this->configuration->parser()->parse($token); 78 | } catch (Exception $e) { 79 | throw new TokenInvalidException('Could not decode token: ' 80 | . $e->getMessage(), $e->getCode(), $e); 81 | } 82 | 83 | if (!$this->configuration->validator()->validate($token, ...$this->configuration->validationConstraints())) { 84 | throw new TokenInvalidException('Token Signature could not be verified.'); 85 | } 86 | 87 | $claims = []; 88 | foreach ($token->claims()->all() as $key => $claim) { 89 | if ($claim instanceof DateTimeInterface) { 90 | $claims[$key] = (int) $claim->getTimestamp(); 91 | } else { 92 | $claims[$key] = is_object($claim) && method_exists($claim, 'getValue') 93 | ? $claim->getValue() 94 | : $claim; 95 | } 96 | } 97 | return $claims; 98 | } 99 | 100 | /** 101 | * Create an instance of the builder with all of the claims applied. 102 | * 103 | * @param array $payload 104 | * @return \Lcobucci\JWT\Token\Builder 105 | */ 106 | protected function getBuilderFromClaims(array $payload) 107 | { 108 | $builder = $this->configuration->builder(); 109 | foreach ($payload as $key => $value) { 110 | $value = $value->getValue(); 111 | switch ($key) { 112 | case RegisteredClaims::ID: 113 | $builder->identifiedBy($value); 114 | break; 115 | case RegisteredClaims::EXPIRATION_TIME: 116 | $builder->expiresAt(DateTimeImmutable::createFromFormat('U', $value)); 117 | break; 118 | case RegisteredClaims::NOT_BEFORE: 119 | $builder->canOnlyBeUsedAfter(DateTimeImmutable::createFromFormat('U', $value)); 120 | break; 121 | case RegisteredClaims::ISSUED_AT: 122 | $builder->issuedAt(DateTimeImmutable::createFromFormat('U', $value)); 123 | break; 124 | case RegisteredClaims::ISSUER: 125 | $builder->issuedBy($value); 126 | break; 127 | case RegisteredClaims::AUDIENCE: 128 | $builder->permittedFor($value); 129 | break; 130 | case RegisteredClaims::SUBJECT: 131 | $builder->relatedTo($value); 132 | break; 133 | default: 134 | $builder->withClaim($key, $value); 135 | } 136 | } 137 | 138 | return $builder; 139 | } 140 | 141 | protected function buildConfiguration() 142 | { 143 | $config = $this->isAsymmetric() 144 | ? Configuration::forAsymmetricSigner( 145 | $this->signer, 146 | $this->getSigningKey(), 147 | $this->getVerificationKey() 148 | ) 149 | : Configuration::forSymmetricSigner($this->signer, $this->getSigningKey()); 150 | 151 | $config->setValidationConstraints( 152 | new SignedWith($this->signer, $this->getVerificationKey()) 153 | ); 154 | 155 | return $config; 156 | } 157 | 158 | protected function isAsymmetric() 159 | { 160 | return is_subclass_of($this->signer, Rsa::class) 161 | || is_subclass_of($this->signer, Ecdsa::class); 162 | } 163 | 164 | protected function getSigningKey() 165 | { 166 | if ($this->isAsymmetric()) { 167 | if (!$privateKey = $this->getPrivateKey()) { 168 | throw new JWTException('Private key is not set.'); 169 | } 170 | 171 | return $this->getKey($privateKey, $this->getPassword() ?? ''); 172 | } 173 | 174 | if (!$secret = $this->getSecret()) { 175 | throw new JWTException('Secret is not set.'); 176 | } 177 | return $this->getKey($secret); 178 | } 179 | 180 | protected function getVerificationKey() 181 | { 182 | if ($this->isAsymmetric()) { 183 | if (!$public = $this->getPublicKey()) { 184 | throw new JWTException('Public key is not set.'); 185 | } 186 | 187 | return $this->getKey($public); 188 | } 189 | 190 | if (!$secret = $this->getSecret()) { 191 | throw new JWTException('Secret is not set.'); 192 | } 193 | 194 | return $this->getKey($secret); 195 | } 196 | 197 | 198 | protected function getSign() 199 | { 200 | if (!isset($this->signers[$this->algo])) { 201 | throw new JWTException('Cloud not find ' . $this->algo . ' algo'); 202 | } 203 | 204 | $signer = $this->signers[$this->algo]; 205 | 206 | if (is_subclass_of($signer, Ecdsa::class)) { 207 | return $signer::create(); 208 | } 209 | 210 | return new $signer(); 211 | } 212 | /** 213 | * Get the signing key instance. 214 | */ 215 | protected function getKey(string $contents, string $passphrase = '') 216 | { 217 | return InMemory::plainText($contents, $passphrase); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/provider/JWT/Provider.php: -------------------------------------------------------------------------------- 1 | keys['public'])) { 19 | return 'file://'. $this->keys['public']; 20 | } 21 | throw new JWTException('Please set public key as the path of pem file.'); 22 | } 23 | 24 | public function getPrivateKey() 25 | { 26 | if (is_file($this->keys['private'])) { 27 | return 'file://'.$this->keys['private']; 28 | } 29 | throw new JWTException('Please set private key as the path of pem file.'); 30 | } 31 | 32 | public function getSecret() 33 | { 34 | return $this->keys; 35 | } 36 | 37 | public function getPassword() 38 | { 39 | return $this->keys['password']; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/provider/storage/Tp5.php: -------------------------------------------------------------------------------- 1 |