-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAbstractToken.php
More file actions
251 lines (221 loc) · 6.57 KB
/
AbstractToken.php
File metadata and controls
251 lines (221 loc) · 6.57 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
<?php
declare(strict_types=1);
namespace Staffbase\plugins\sdk;
use DateInterval;
use Exception;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\Plain;
use Lcobucci\JWT\Validation\Constraint;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Staffbase\plugins\sdk\Exceptions\SSOAuthenticationException;
use Staffbase\plugins\sdk\Exceptions\SSOException;
abstract class AbstractToken
{
private Plain $token;
private Key $signerKey;
private Configuration $config;
/**
* @var Constraint[]
*/
private array $constraints;
/**
* Constructor
*
* @param string $appSecret Either a PEM key or a file:// URL.
* @param non-empty-string $tokenData The token text.
* @param Signer $signer The algorithm which is used to sign the token
* @param Constraint[] $constrains constrains
*
* @throws SSOAuthenticationException
* @throws SSOException on invalid parameters.
*/
public function __construct(string $appSecret, protected string $tokenData, Signer $signer, array $constrains = [])
{
if (!trim($appSecret)) {
throw new SSOException('Parameter appSecret for SSOToken is empty.');
}
if (!trim($tokenData)) {
throw new SSOException('Parameter tokenData for SSOToken is empty.');
}
$this->setSignerKey(trim($appSecret));
$this->setConfig(Configuration::forSymmetricSigner($signer, $this->getSignerKey()));
$this->constraints = [
new SignedWith($signer, $this->getSignerKey()),
...$constrains,
];
}
/**
* Creates and validates an SSO token.
*
*/
protected function parseToken(): void
{
// parse text
$token = $this->config->parser()->parse($this->tokenData);
if (!$token instanceof Plain) {
throw new \RuntimeException('Parsed token is not a Plain token');
}
$this->token = $token;
}
/**
* Creates and validates an SSO token.
*
* @throws SSOAuthenticationException if the parsing/verification/validation of the token fails.
*/
protected function validateToken(): void
{
try {
$this->config->validator()->assert($this->token, ...$this->constraints);
} catch (RequiredConstraintsViolated $violation) {
throw new SSOAuthenticationException($violation->getMessage());
}
}
/**
* Test if a claim is set.
*
* @param string $claim name.
*/
protected function hasClaim(string $claim): bool
{
if (empty($claim)) {
return false;
}
return $this->token->claims()->has($claim);
}
/**
* Get a claim without checking for existence.
*
* @param string $claim name.
*
* @return mixed
*/
/**
* Get a claim without checking for existence.
*
* @param string $claim name.
*
* @return mixed
*/
protected function getClaim(string $claim): mixed
{
if (empty($claim)) {
return null;
}
return $this->token->claims()->get($claim);
}
/**
* Get an array of all available claims and their values.
*
* @return array<string, mixed>
*/
protected function getAllClaims(): array
{
return $this->token->claims()->all();
}
/**
* Translate a base64 string to PEM encoded public key.
*
* @param string $data base64 encoded key
*
* @return string PEM encoded key
*/
public static function base64ToPEMPublicKey(string $data): string
{
if (empty($data)) {
throw new SSOException('Empty base64 data provided for PEM conversion.');
}
$data = strtr($data, [
"\r" => "",
"\n" => "",
]);
if (empty($data)) {
throw new SSOException('Base64 data is empty after cleanup.');
}
return
"-----BEGIN PUBLIC KEY-----\n"
. chunk_split($data, 64)
. "-----END PUBLIC KEY-----\n";
}
/**
* Set the configuration
*
* @param Configuration $value
*/
public function setConfig(Configuration $value): void
{
$this->config = $value;
}
/**
* Get the configuration
*/
public function getConfig(): Configuration
{
return $this->config;
}
/**
* Creates a key from the secret and stores it to the property
* @param string $secret
*/
public function setSignerKey(string $secret): void
{
$this->signerKey = $this->getKey($secret);
}
/**
* Get the Signer key
*/
public function getSignerKey(): Key
{
return $this->signerKey;
}
/**
* Decides between the new key methods, the JWT library offers
*
* @param string $appSecret
*/
private function getKey(string $appSecret): Key
{
// Ensure the app secret is not empty to satisfy strict non-empty-string requirements
if (!trim($appSecret)) {
throw new SSOException('Empty appSecret provided when creating signer key.');
}
if (strpos($appSecret, '-----') === 0) {
if (empty($appSecret)) {
throw new SSOException('Empty PEM key provided.');
}
$key = InMemory::plainText($appSecret);
} elseif (strpos($appSecret, 'file://') === 0) {
if (empty($appSecret)) {
throw new SSOException('Empty file path provided.');
}
$key = InMemory::file($appSecret);
} else {
$pem = self::base64ToPEMPublicKey($appSecret);
// After our validation in base64ToPEMPublicKey, we know $pem is non-empty
/** @var non-empty-string $pem */
$key = InMemory::plainText($pem);
}
return $key;
}
/**
* Formats the leeway integer value into a DateInterval as this is
* needed by the JWT library
*
* @param int $leeway count of seconds added to current timestamp
* @return DateInterval DateInterval
*/
protected function getLeewayInterval(int $leeway): DateInterval
{
$leewayInterval = "PT{$leeway}S";
try {
$interval = new DateInterval($leewayInterval);
} catch (Exception $e) {
error_log("Wrong date interval $leewayInterval");
$interval = new DateInterval('PT0S');
}
return $interval;
}
}