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