12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace ln\services;
- use ln\exceptions\AuthException;
- use Firebase\JWT\BeforeValidException;
- use Firebase\JWT\ExpiredException;
- use Firebase\JWT\JWT;
- use Firebase\JWT\SignatureInvalidException;
- use think\facade\Config;
- use UnexpectedValueException;
- class JwtTokenService
- {
-
- public function createToken(int $id, string $type, $exp, array $params = [])
- {
- $time = time();
- $host = app('request')->host();
- $params += [
- 'iss' => $host,
- 'aud' => $host,
- 'iat' => $time,
- 'nbf' => $time,
- 'exp' => $exp,
- ];
- $params['jti'] = [$id, $type];
- $token = JWT::encode($params, Config::get('app.app_key', 'default'));
- $params['token'] = $token;
- $params['out'] = $exp * 60 * 60;
- return $params;
- }
-
- public function parseToken(string $token)
- {
- return JWT::decode($token, Config::get('app.app_key', 'default'), array('HS256'));
- }
-
- public function decode(string $token)
- {
- $tks = explode('.', $token);
- if (count($tks) != 3)
- throw new AuthException('Invalid token');
- if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($tks[1])))
- throw new AuthException('Invalid token');
- return $payload;
- }
- }
|