1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only |
5
|
|
|
* SPDX-FileCopyrightText: Copyright 2023 grommunio GmbH |
6
|
|
|
* |
7
|
|
|
* Object class to parse a JSON Web Token. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
class Token { |
11
|
|
|
public $token_header; |
12
|
|
|
public $token_payload; |
13
|
|
|
public $token_signature; |
14
|
|
|
public $signed; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Constructor loading a token string received from Keycloak. |
18
|
|
|
* |
19
|
|
|
* @param string $_raw holding |
20
|
|
|
*/ |
21
|
|
|
public function __construct(protected $_raw) { |
22
|
|
|
if ($this->_raw) { |
23
|
|
|
try { |
24
|
|
|
$parts = explode('.', (string) $this->_raw); |
25
|
|
|
$th = base64_decode($parts[0]); |
26
|
|
|
$tp = base64_decode($parts[1]); |
27
|
|
|
$ts = base64_decode($parts[2]); |
28
|
|
|
$this->token_header = json_decode($th, true); |
29
|
|
|
$this->token_payload = json_decode($tp, true); |
30
|
|
|
$this->token_signature = $ts; |
31
|
|
|
$this->signed = $parts[0] . '.' . $parts[1]; |
32
|
|
|
} |
33
|
|
|
catch (Exception) { |
34
|
|
|
$this->token_payload = [ |
35
|
|
|
'expires_at' => 0, |
36
|
|
|
]; |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Returns the signature of the token. |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function get_signature() { |
47
|
|
|
return $this->token_signature; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Indicates if the token was singned. |
52
|
|
|
* |
53
|
|
|
* @return bool |
54
|
|
|
*/ |
55
|
|
|
public function get_signed() { |
56
|
|
|
return $this->signed; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Returns raw payload. |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
|
|
public function get_payload() { |
65
|
|
|
return $this->_raw; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Returns the value of a claim if it's defined in the payload. |
70
|
|
|
* Otherwise returns an empty string. |
71
|
|
|
* |
72
|
|
|
* @param string $claim |
73
|
|
|
* |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
public function get_claims($claim) { |
77
|
|
|
return $this->token_payload[$claim] ?? ''; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Checks if a token is expired comparing to the current time. |
82
|
|
|
* |
83
|
|
|
* @return bool |
84
|
|
|
*/ |
85
|
|
|
public function is_expired() { |
86
|
|
|
return $this->token_payload['exp'] < time() || $this->token_payload['iat'] < time() - 86400; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|