-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOpenIDConnect.php
More file actions
546 lines (476 loc) · 16.1 KB
/
Copy pathOpenIDConnect.php
File metadata and controls
546 lines (476 loc) · 16.1 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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
<?php
namespace Drupal\os2forms_nemlogin_openid_connect\Plugin\os2web\NemloginAuthProvider;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\LocalRedirectResponse;
use Drupal\Core\Routing\TrustedRedirectResponse;
use Drupal\Core\Url;
use Drupal\os2forms_nemlogin_openid_connect\Controller\OpenIDConnectController;
use Drupal\os2web_audit\Service\Logger;
use Drupal\os2web_nemlogin\Form\AuthProviderBaseSettingsForm;
use Drupal\os2web_nemlogin\Plugin\AuthProviderBase;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
/**
* Defines a plugin for Nemlogin auth via OpenID Connect.
*
* @AuthProvider(
* id = "OpenIDConnect",
* label = @Translation("OpenIDConnect Nemlogin auth provider"),
* )
*/
class OpenIDConnect extends AuthProviderBase {
use LoggerTrait;
use LoggerAwareTrait;
public const SESSION_TOKEN = 'os2forms_nemlogin_openid_connect.user_token';
public const KEY = 'nemlogin_openid_connect_key';
public const SECRET_PROVIDER = 'secret_provider';
public const PROVIDER_TYPE_FORM = 'form';
public const PROVIDER_TYPE_KEY = 'key';
public const FETCH_ONCE = 'nemlogin_openid_connect_fetch_once';
public const POST_LOGOUT_REDIRECT_URI = 'nemlogin_openid_connect_post_logout_redirect_uri';
public const USER_CLAIMS = 'nemlogin_openid_connect_user_claims';
public const DISCOVERY_URL = 'nemlogin_openid_connect_discovery_url';
public const CLIENT_ID = 'nemlogin_openid_connect_client_id';
public const CLIENT_SECRET = 'nemlogin_openid_connect_client_secret';
/**
* Fetch only mode flag.
*
* @var bool
*/
private $fetchOnce = FALSE;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
private $requestStack;
/**
* The session.
*
* @var \Symfony\Component\HttpFoundation\Session\SessionInterface
*/
private $session;
/**
* The audit logger.
*
* @var \Drupal\os2web_audit\Service\Logger
*/
private $auditLogger;
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $configuration
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
RequestStack $requestStack,
SessionInterface $session,
LoggerInterface $logger,
Logger $auditLogger,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->session = $session;
$this->requestStack = $requestStack;
$this->setLogger($logger);
$this->auditLogger = $auditLogger;
$this->values = $this->getToken() ?? [];
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $configuration
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// Shamelessly lifted from Drupal\os2web_nemlogin\Plugin\AuthProviderBase.
// Swapping config with a values from config object.
$configObject = $container->get('config.factory')->get(AuthProviderBaseSettingsForm::$configName);
if ($configurationSerialized = $configObject->get($plugin_id)) {
$configuration = unserialize($configurationSerialized, ['allowed_classes' => FALSE]);
}
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('request_stack'),
$container->get('session'),
$container->get('logger.channel.os2forms_nemlogin_openid_connect'),
$container->get('os2web_audit.logger')
);
}
/**
* {@inheritdoc}
*/
public function isInitialized() {
$configuration = $this->getConfiguration();
if (!empty($configuration[self::DISCOVERY_URL])) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function isAuthenticated() {
// If user has any authenticated data consider it as authenticated.
return !empty($this->values);
}
/**
* {@inheritdoc}
*/
public function isAuthenticatedPerson() {
// We have to fetch value via parent, in order to avoid possible deletion
// of value if "fetchOnce" flag is TRUE.
// It's important that CVR key is empty, since
// users often login on behalf of company as themselves
// i.e. values may contain both a cpr and cvr value.
if (!empty(parent::fetchValue('cpr')) && empty(parent::fetchValue('cvr'))) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function isAuthenticatedCompany() {
// We have to fetch value via parent, in order to avoid possible deletion
// of value if "fetchOnce" flag is TRUE.
if (!empty(parent::fetchValue('cvr'))) {
return TRUE;
}
return FALSE;
}
/**
* {@inheritdoc}
*
* @return \Symfony\Component\HttpFoundation\Response
* The response.
*/
public function login() {
$request = $this->requestStack->getCurrentRequest();
$token = $this->getToken();
if (NULL === $token) {
// Pass the current request uri on to the controller to tell it where to
// return to after authentication.
$url = Url::fromRoute('os2forms_nemlogin_openid_connect.openid_connect_authenticate', [
'id' => $this->getPluginId(),
OpenIDConnectController::QUERY_LOCATION_NAME => $request->getRequestUri(),
])
->toString(TRUE)
->getGeneratedUrl();
return (new LocalRedirectResponse($url))
->send();
}
$this->values = $token;
$msg = sprintf('Login succeeded through %s with claims, %s', $this->getPluginId(), $this->getClaimDataString());
$this->auditLogger->info('OpenIdConnect', $msg);
return (new TrustedRedirectResponse($this->getReturnUrl()))
->send();
}
/**
* {@inheritdoc}
*
* @return \Symfony\Component\HttpFoundation\Response
* The response.
*/
public function logout() {
$msg = sprintf('Logout succeeded through %s with claims, %s', $this->getPluginId(), $this->getClaimDataString());
$this->getToken(TRUE);
$this->values = [];
$url = Url::fromRoute('os2forms_nemlogin_openid_connect.openid_connect_end_session', [
'id' => $this->getPluginId(),
])
->toString(TRUE)
->getGeneratedUrl();
$this->auditLogger->info('OpenIdConnect', $msg);
return (new TrustedRedirectResponse($url))
->send();
}
/**
* Set token.
*
* Used by authentication controller to set the result of the actual user
* authentication.
*
* @param array $token
* The user token.
*
* @return $this
*
* @phpstan-param array<string, mixed> $token
*/
public function setToken(array $token): self {
$this->session->set($this->getTokenKey(), $token);
return $this;
}
/**
* Get token.
*
* @phpstan-return array<string, mixed>|null
*/
private function getToken(bool $clear = FALSE): ?array {
$tokenKey = $this->getTokenKey();
$token = $this->session->get($tokenKey);
if ($clear) {
$this->session->remove($tokenKey);
}
return $token;
}
/**
* {@inheritdoc}
*
* @phpstan-param string|array<string, mixed> $key
*/
public function fetchValue($key) {
$value = parent::fetchValue($key);
// @todo handle this
if ($this->fetchOnce) {
unset($this->values[$key]);
}
return $value;
}
/**
* {@inheritdoc}
*
* @return array
* The default configuration.
*
* @phpstan-return array<string, mixed>
*/
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
self::SECRET_PROVIDER => self::PROVIDER_TYPE_FORM,
self::DISCOVERY_URL => '',
self::CLIENT_ID => '',
self::CLIENT_SECRET => '',
self::KEY => '',
self::FETCH_ONCE => '',
self::POST_LOGOUT_REDIRECT_URI => '',
self::USER_CLAIMS => '',
];
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $form
* @phpstan-return array<string, mixed>
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
$form[self::SECRET_PROVIDER] = [
'#type' => 'select',
'#title' => $this->t('Provider'),
'#options' => [
self::PROVIDER_TYPE_FORM => $this->t('Form'),
self::PROVIDER_TYPE_KEY => $this->t('Key'),
],
'#default_value' => $this->configuration[self::SECRET_PROVIDER] ?? self::PROVIDER_TYPE_FORM,
];
$form[self::DISCOVERY_URL] = [
'#type' => 'textfield',
'#title' => $this->t('OpenID Connect Discovery url'),
// Our urls are very long.
'#maxlength' => 256,
'#default_value' => $this->configuration[self::DISCOVERY_URL] ?? NULL,
'#description' => $this->t('OpenID Connect Discovery url (cf. <a href="https://swagger.io/docs/specification/authentication/openid-connect-discovery/">https://swagger.io/docs/specification/authentication/openid-connect-discovery/</a>)'),
'#states' => [
'visible' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
'required' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
],
];
$form[self::CLIENT_ID] = [
'#type' => 'textfield',
'#title' => $this->t('Client id'),
'#default_value' => $this->configuration[self::CLIENT_ID] ?? NULL,
'#states' => [
'visible' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
'required' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
],
];
$form[self::CLIENT_SECRET] = [
'#type' => 'textfield',
'#title' => $this->t('Client secret'),
'#default_value' => $this->configuration[self::CLIENT_SECRET] ?? NULL,
'#states' => [
'visible' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
'required' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_FORM]],
],
],
];
$form[self::KEY] = [
'#type' => 'key_select',
'#key_filters' => [
'type' => 'os2web_key_oidc',
],
'#title' => $this->t('Key'),
'#default_value' => $this->configuration[self::KEY] ?? NULL,
'#states' => [
'visible' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_KEY]],
],
'required' => [
[':input[name="secret_provider"]' => ['value' => self::PROVIDER_TYPE_KEY]],
],
],
];
$form[self::FETCH_ONCE] = [
'#type' => 'checkbox',
'#title' => $this->t('Use fetch only mode.'),
'#default_value' => $this->configuration[self::FETCH_ONCE] ?? FALSE,
'#description' => $this->t('User will be logged out immediately after login. User data will be removed from session after first retrieving'),
];
$form[self::POST_LOGOUT_REDIRECT_URI] = [
'#type' => 'textfield',
'#title' => $this->t('Post logout redirect url'),
'#required' => TRUE,
'#default_value' => $this->configuration[self::POST_LOGOUT_REDIRECT_URI] ?? NULL,
'#description' => $this->t('Url to redirect to after logout. Can be an internal path, e.g. <code>/node/87</code>, or an external url, e.g. <code>https://aarhus.dk</code>'),
];
$form[self::USER_CLAIMS] = [
'#type' => 'textarea',
'#title' => $this->t('User claims'),
'#description' => $this->t('Describe user claims for use when comparing user values.<br/>Each line must be on the form <code>«claim»: «display name»</code>, e.g.<br/><br/><code>cpr: CPR-nummer<br/>email: E-mailadresse</code>'),
'#default_value' => $this->configuration[self::USER_CLAIMS] ?? NULL,
];
return $form;
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $form
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state): void {
if (self::PROVIDER_TYPE_FORM === $form_state->getValue(self::SECRET_PROVIDER)) {
$discoveryUrl = $form_state->getValue(self::DISCOVERY_URL);
if (!UrlHelper::isValid($discoveryUrl, TRUE)) {
$form_state->setErrorByName(self::DISCOVERY_URL, $this->t('Discovery url is not valid'));
}
}
$redirectUrl = $form_state->getValue(self::POST_LOGOUT_REDIRECT_URI);
try {
UrlHelper::isExternal($redirectUrl) ? Url::fromUri($redirectUrl) : Url::fromUserInput($redirectUrl);
}
catch (\Exception $exception) {
$form_state->setErrorByName(self::POST_LOGOUT_REDIRECT_URI, $this->t('Post logout redirect url is not valid (@message)', ['@message' => $exception->getMessage()]));
}
$claims = $form_state->getValue(self::USER_CLAIMS);
try {
$values = Yaml::parse($claims);
foreach ($values as $name => $value) {
if (!is_string($name)) {
$form_state->setErrorByName(
self::USER_CLAIMS,
$this->t('Name (@name) must be a string; found @type.', [
'@name' => $name,
'@type' => gettype($name),
])
);
break;
}
if (!is_string($value)) {
$form_state->setErrorByName(
self::USER_CLAIMS,
$this->t('Value for “@name” must be a string; found @type.', [
'@name' => $name,
'@type' => gettype($value),
])
);
break;
}
}
}
catch (ParseException $exception) {
$form_state->setErrorByName(self::USER_CLAIMS, $this->t('Invalid claims (@message)', ['@message' => $exception->getMessage()]));
}
}
/**
* {@inheritdoc}
*
* @phpstan-param array<string, mixed> $form
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
$configuration = $this->getConfiguration();
$configuration[self::SECRET_PROVIDER] = $form_state->getValue(self::SECRET_PROVIDER);
$configuration[self::DISCOVERY_URL] = $form_state->getValue(self::DISCOVERY_URL);
$configuration[self::CLIENT_ID] = $form_state->getValue(self::CLIENT_ID);
$configuration[self::CLIENT_SECRET] = $form_state->getValue(self::CLIENT_SECRET);
$configuration[self::KEY] = $form_state->getValue(self::KEY);
$configuration[self::FETCH_ONCE] = $form_state->getValue(self::FETCH_ONCE);
$configuration[self::POST_LOGOUT_REDIRECT_URI] = $form_state->getValue(self::POST_LOGOUT_REDIRECT_URI);
$configuration[self::USER_CLAIMS] = $form_state->getValue(self::USER_CLAIMS);
$this->setConfiguration($configuration);
}
/**
* {@inheritdoc}
*
* @phpstan-param mixed $level
* @phpstan-param string $message
* @phpstan-param array<string, mixed> $context
*/
public function log($level, $message, array $context = []): void {
if (NULL !== $this->logger) {
$this->logger->log($level, $message, $context);
}
}
/**
* Get string of claim data.
*/
private function getClaimDataString(): string {
$claimKeys = $this->getClaimKeys();
$claims = [];
foreach ($claimKeys as $claimKey) {
$claimValue = $this->fetchValue($claimKey);
if (!empty($claimValue)) {
$claims[] = $claimKey . ': ' . $claimValue;
}
else {
$this->logger->debug(sprintf('OpenIDConnect (%s): Missing claim %s', $this->getPluginId(), $claimKey));
}
}
return implode(', ', $claims);
}
/**
* Get claim keys.
*
* @phpstan-return array<int, mixed>
*/
private function getClaimKeys(): array {
// Example claim configuration:
// "name: Navn\r\nemail: E-mailadresse".
$claims = $this->configuration['nemlogin_openid_connect_user_claims'];
if (empty($claims)) {
return [];
}
$pairs = explode("\r\n", $claims);
$keys = [];
foreach ($pairs as $pair) {
$keyValue = explode(': ', $pair);
$keys[] = $keyValue[0];
}
return $keys;
}
/**
* Get unique token key.
*/
private function getTokenKey(): string {
return self::SESSION_TOKEN . '_' . $this->getPluginId();
}
}