-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclass.token.php
90 lines (82 loc) · 1.79 KB
/
class.token.php
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
/*
* SPDX-License-Identifier: AGPL-3.0-only
* SPDX-FileCopyrightText: Copyright 2023 grommunio GmbH
*
* Object class to parse a JSON Web Token.
*/
class Token {
public $token_header;
public $token_payload;
public $token_signature;
public $signed;
protected $_raw;
/**
* Constructor loading a token string received from Keycloak.
*
* @param string $keycloak_token holding
*/
public function __construct($keycloak_token) {
$this->_raw = $keycloak_token;
if ($keycloak_token) {
try {
$parts = explode('.', $keycloak_token);
$th = base64_decode($parts[0]);
$tp = base64_decode($parts[1]);
$ts = base64_decode($parts[2]);
$this->token_header = json_decode($th, true);
$this->token_payload = json_decode($tp, true);
$this->token_signature = $ts;
$this->signed = $parts[0] . '.' . $parts[1];
}
catch (Exception $e) {
$this->token_payload = [
'expires_at' => 0,
];
}
}
}
/**
* Returns the signature of the token.
*
* @return string
*/
public function get_signature() {
return $this->token_signature;
}
/**
* Indicates if the token was singned.
*
* @return bool
*/
public function get_signed() {
return $this->signed;
}
/**
* Returns raw payload.
*
* @return string
*/
public function get_payload() {
return $this->_raw;
}
/**
* Returns the value of a claim if it's defined in the payload.
* Otherwise returns an empty string.
*
* @param string $claim
*
* @return string
*/
public function get_claims($claim) {
return $this->token_payload[$claim] ?? '';
}
/**
* Checks if a token is expired comparing to the current time.
*
* @return bool
*/
public function is_expired() {
return $this->token_payload['exp'] < time() || $this->token_payload['iat'] < time() - 86400;
}
}