|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SoliDry\Helpers; |
|
4
|
|
|
|
|
5
|
|
|
use Lcobucci\JWT\Builder; |
|
6
|
|
|
use Lcobucci\JWT\Signer\Hmac\Sha256; |
|
7
|
|
|
use Lcobucci\JWT\Token; |
|
8
|
|
|
use Lcobucci\JWT\ValidationData; |
|
9
|
|
|
use SoliDry\Types\ConfigInterface; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Class Jwt |
|
13
|
|
|
* @package SoliDry\Helpers |
|
14
|
|
|
*/ |
|
15
|
|
|
class Jwt |
|
16
|
|
|
{ |
|
17
|
|
|
private const JWT_SECRETE_KEY = 'app.jwt_secret'; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Fulfills the token with data and signs it with key |
|
21
|
|
|
* |
|
22
|
|
|
* @param int $uid |
|
23
|
|
|
* |
|
24
|
|
|
* @return string |
|
25
|
|
|
* @throws \BadMethodCallException |
|
26
|
|
|
*/ |
|
27
|
|
|
public static function create(int $uid) : string |
|
28
|
|
|
{ |
|
29
|
|
|
$signer = new Sha256(); |
|
30
|
|
|
|
|
31
|
|
|
$generatedId = uniqid('', true); |
|
32
|
|
|
return (new Builder())->setIssuer($_SERVER['HTTP_HOST'])// Configures the issuer (iss claim) |
|
33
|
|
|
->setAudience($_SERVER['HTTP_HOST'])// Configures the audience (aud claim) |
|
34
|
|
|
->setId($generatedId, true)// Configures the id (jti claim), replicating as a header item |
|
35
|
|
|
->setIssuedAt(time())// Configures the time that the token was issue (iat claim) |
|
36
|
|
|
->setNotBefore(time() + ConfigHelper::getNestedParam(ConfigInterface::JWT, ConfigInterface::ACTIVATE))// Configures the time that the token can be used (nbf claim) |
|
37
|
|
|
->setExpiration(time() + ConfigHelper::getNestedParam(ConfigInterface::JWT, ConfigInterface::EXPIRES))// Configures the expiration time of the token (nbf claim) |
|
38
|
|
|
->set('uid', $uid)// Configures a new claim, called "uid" |
|
39
|
|
|
->sign($signer, $generatedId . config(self::JWT_SECRETE_KEY) . $uid)// glue uniqid + uid |
|
40
|
|
|
->getToken(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Verifies token data and key |
|
45
|
|
|
* |
|
46
|
|
|
* @param Token $token |
|
47
|
|
|
* @param string $generatedId |
|
48
|
|
|
* |
|
49
|
|
|
* @return bool |
|
50
|
|
|
* @throws \BadMethodCallException |
|
51
|
|
|
* @throws \OutOfBoundsException |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function verify(Token $token): bool |
|
54
|
|
|
{ |
|
55
|
|
|
$generatedId = $token->getHeader('jti'); |
|
56
|
|
|
|
|
57
|
|
|
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp) |
|
58
|
|
|
$data->setIssuer($_SERVER['HTTP_HOST']); |
|
59
|
|
|
$data->setAudience($_SERVER['HTTP_HOST']); |
|
60
|
|
|
$data->setId($generatedId); |
|
61
|
|
|
|
|
62
|
|
|
$signer = new Sha256(); |
|
63
|
|
|
$uid = $token->getClaim('uid'); |
|
64
|
|
|
return $token->validate($data) && $token->verify($signer, $generatedId . config(self::JWT_SECRETE_KEY) . $uid); |
|
65
|
|
|
} |
|
66
|
|
|
} |