-
Notifications
You must be signed in to change notification settings - Fork 145
Expand file tree
/
Copy pathJWTManager.php
More file actions
90 lines (81 loc) · 2.7 KB
/
Copy pathJWTManager.php
File metadata and controls
90 lines (81 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter Shield.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Shield\Authentication;
use CodeIgniter\I18n\Time;
use CodeIgniter\Shield\Authentication\JWT\JWSDecoder;
use CodeIgniter\Shield\Authentication\JWT\JWSEncoder;
use CodeIgniter\Shield\Entities\User;
use stdClass;
/**
* JWT Manager
*/
class JWTManager
{
public function __construct(
protected ?Time $clock = null,
protected ?JWSEncoder $jwsEncoder = null,
protected ?JWSDecoder $jwsDecoder = null,
) {
$this->clock = $clock ?? new Time();
$this->jwsEncoder = $jwsEncoder ?? new JWSEncoder(null, $this->clock);
$this->jwsDecoder = $jwsDecoder ?? new JWSDecoder();
}
/**
* Issues Signed JWT (JWS) for a User
*
* @param array $claims The payload items.
* @param int|null $ttl Time to live in seconds.
* @param string $keyset The key group.
* The array key of Config\AuthJWT::$keys.
* @param array<string, string>|null $headers An array with header elements to attach.
*/
public function generateToken(
User $user,
array $claims = [],
?int $ttl = null,
$keyset = 'default',
?array $headers = null,
): string {
$payload = array_merge(
$claims,
[
'sub' => (string) $user->id, // subject
],
);
return $this->issue($payload, $ttl, $keyset, $headers);
}
/**
* Issues Signed JWT (JWS)
*
* @param array $claims The payload items.
* @param int|null $ttl Time to live in seconds.
* @param string $keyset The key group.
* The array key of Config\AuthJWT::$keys.
* @param array<string, string>|null $headers An array with header elements to attach.
*/
public function issue(
array $claims,
?int $ttl = null,
$keyset = 'default',
?array $headers = null,
): string {
return $this->jwsEncoder->encode($claims, $ttl, $keyset, $headers);
}
/**
* Returns payload of the JWT
*
* @param string $keyset The key group. The array key of Config\AuthJWT::$keys.
*/
public function parse(string $encodedToken, $keyset = 'default'): stdClass
{
return $this->jwsDecoder->decode($encodedToken, $keyset);
}
}