5 use BookStack\Activity\ActivityType;
6 use BookStack\Facades\Theme;
7 use BookStack\Theming\ThemeEvents;
8 use BookStack\Uploads\UserAvatars;
9 use BookStack\Users\Models\Role;
10 use BookStack\Users\Models\User;
11 use GuzzleHttp\Psr7\Response;
12 use Illuminate\Testing\TestResponse;
13 use Tests\Helpers\OidcJwtHelper;
16 class OidcTest extends TestCase
18 protected string $keyFilePath;
21 protected function setUp(): void
24 // Set default config for OpenID Connect
26 $this->keyFile = tmpfile();
27 $this->keyFilePath = 'file://' . stream_get_meta_data($this->keyFile)['uri'];
28 file_put_contents($this->keyFilePath, OidcJwtHelper::publicPemKey());
31 'auth.method' => 'oidc',
32 'auth.defaults.guard' => 'oidc',
33 'oidc.name' => 'SingleSignOn-Testing',
34 'oidc.display_name_claims' => 'name',
35 'oidc.client_id' => OidcJwtHelper::defaultClientId(),
36 'oidc.client_secret' => 'testpass',
37 'oidc.jwt_public_key' => $this->keyFilePath,
38 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
39 'oidc.authorization_endpoint' => 'https://oidc.local/auth',
40 'oidc.token_endpoint' => 'https://oidc.local/token',
41 'oidc.userinfo_endpoint' => 'https://oidc.local/userinfo',
42 'oidc.discover' => false,
43 'oidc.dump_user_details' => false,
44 'oidc.additional_scopes' => '',
45 'odic.fetch_avatar' => false,
46 'oidc.user_to_groups' => false,
47 'oidc.groups_claim' => 'group',
48 'oidc.remove_from_groups' => false,
49 'oidc.external_id_claim' => 'sub',
50 'oidc.end_session_endpoint' => false,
54 protected function tearDown(): void
57 if (file_exists($this->keyFilePath)) {
58 unlink($this->keyFilePath);
62 public function test_login_option_shows_on_login_page()
64 $req = $this->get('/login');
65 $req->assertSeeText('SingleSignOn-Testing');
66 $this->withHtml($req)->assertElementExists('form[action$="/oidc/login"][method=POST] button');
69 public function test_oidc_routes_are_only_active_if_oidc_enabled()
71 config()->set(['auth.method' => 'standard']);
72 $routes = ['/login' => 'post', '/callback' => 'get'];
73 foreach ($routes as $uri => $method) {
74 $req = $this->call($method, '/oidc' . $uri);
75 $this->assertPermissionError($req);
79 public function test_forgot_password_routes_inaccessible()
81 $resp = $this->get('/password/email');
82 $this->assertPermissionError($resp);
84 $resp = $this->post('/password/email');
85 $this->assertPermissionError($resp);
87 $resp = $this->get('/password/reset/abc123');
88 $this->assertPermissionError($resp);
90 $resp = $this->post('/password/reset');
91 $this->assertPermissionError($resp);
94 public function test_standard_login_routes_inaccessible()
96 $resp = $this->post('/login');
97 $this->assertPermissionError($resp);
100 public function test_logout_route_functions()
102 $this->actingAs($this->users->editor());
103 $this->post('/logout');
104 $this->assertFalse(auth()->check());
107 public function test_user_invite_routes_inaccessible()
109 $resp = $this->get('/register/invite/abc123');
110 $this->assertPermissionError($resp);
112 $resp = $this->post('/register/invite/abc123');
113 $this->assertPermissionError($resp);
116 public function test_user_register_routes_inaccessible()
118 $resp = $this->get('/register');
119 $this->assertPermissionError($resp);
121 $resp = $this->post('/register');
122 $this->assertPermissionError($resp);
125 public function test_login()
127 $req = $this->post('/oidc/login');
128 $redirect = $req->headers->get('location');
130 $this->assertStringStartsWith('https://oidc.local/auth', $redirect, 'Login redirects to SSO location');
131 $this->assertFalse($this->isAuthenticated());
132 $this->assertStringContainsString('scope=openid%20profile%20email', $redirect);
133 $this->assertStringContainsString('client_id=' . OidcJwtHelper::defaultClientId(), $redirect);
134 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $redirect);
137 public function test_login_success_flow()
140 $this->post('/oidc/login');
141 $state = session()->get('oidc_state');
143 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
145 'sub' => 'benny1010101',
148 // Callback from auth provider
149 // App calls token endpoint to get id token
150 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
151 $resp->assertRedirect('/');
152 $this->assertEquals(1, $transactions->requestCount());
153 $tokenRequest = $transactions->latestRequest();
154 $this->assertEquals('https://oidc.local/token', (string) $tokenRequest->getUri());
155 $this->assertEquals('POST', $tokenRequest->getMethod());
156 $this->assertEquals('Basic ' . base64_encode(OidcJwtHelper::defaultClientId() . ':testpass'), $tokenRequest->getHeader('Authorization')[0]);
157 $this->assertStringContainsString('grant_type=authorization_code', $tokenRequest->getBody());
158 $this->assertStringContainsString('code=SplxlOBeZQQYbYS6WxSbIA', $tokenRequest->getBody());
159 $this->assertStringContainsString('redirect_uri=' . urlencode(url('/oidc/callback')), $tokenRequest->getBody());
161 $this->assertTrue(auth()->check());
162 $this->assertDatabaseHas('users', [
164 'external_auth_id' => 'benny1010101',
165 'email_confirmed' => false,
169 $this->assertActivityExists(ActivityType::AUTH_LOGIN, null, "oidc; ({$user->id}) Barry Scott");
172 public function test_login_uses_custom_additional_scopes_if_defined()
175 'oidc.additional_scopes' => 'groups, badgers',
178 $redirect = $this->post('/oidc/login')->headers->get('location');
180 $this->assertStringContainsString('scope=openid%20profile%20email%20groups%20badgers', $redirect);
183 public function test_callback_fails_if_no_state_present_or_matching()
185 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
186 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
188 $this->post('/oidc/login');
189 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=abc124');
190 $this->assertSessionError('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
193 public function test_dump_user_details_option_outputs_as_expected()
195 config()->set('oidc.dump_user_details', true);
197 $resp = $this->runLogin([
202 $resp->assertStatus(200);
206 'iss' => OidcJwtHelper::defaultIssuer(),
207 'aud' => OidcJwtHelper::defaultClientId(),
209 $this->assertFalse(auth()->check());
212 public function test_auth_fails_if_no_email_exists_in_user_data()
214 config()->set('oidc.userinfo_endpoint', null);
221 $this->assertSessionError('Could not find an email address, for this user, in the data provided by the external authentication system');
224 public function test_auth_fails_if_already_logged_in()
233 $this->assertSessionError('Already logged in');
236 public function test_auth_login_as_existing_user()
238 $editor = $this->users->editor();
239 $editor->external_auth_id = 'benny505';
242 $this->assertFalse(auth()->check());
249 $this->assertTrue(auth()->check());
250 $this->assertEquals($editor->id, auth()->user()->id);
253 public function test_auth_login_as_existing_user_email_with_different_auth_id_fails()
255 $editor = $this->users->editor();
256 $editor->external_auth_id = 'editor101';
259 $this->assertFalse(auth()->check());
261 $resp = $this->runLogin([
262 'email' => $editor->email,
265 $resp = $this->followRedirects($resp);
267 $resp->assertSeeText('A user with the email ' . $editor->email . ' already exists but with different credentials.');
268 $this->assertFalse(auth()->check());
271 public function test_auth_login_with_invalid_token_fails()
273 $resp = $this->runLogin([
276 $resp = $this->followRedirects($resp);
278 $resp->assertSeeText('ID token validation failed with error: Missing token subject value');
279 $this->assertFalse(auth()->check());
282 public function test_auth_fails_if_endpoints_start_with_https()
284 $endpointConfigKeys = [
285 'oidc.token_endpoint' => 'tokenEndpoint',
286 'oidc.authorization_endpoint' => 'authorizationEndpoint',
287 'oidc.userinfo_endpoint' => 'userinfoEndpoint',
290 foreach ($endpointConfigKeys as $endpointConfigKey => $endpointName) {
291 $logger = $this->withTestLogger();
292 $original = config()->get($endpointConfigKey);
293 $new = str_replace('https://', 'http://', $original);
294 config()->set($endpointConfigKey, $new);
296 $this->withoutExceptionHandling();
299 $resp = $this->runLogin();
300 $resp->assertRedirect('/login');
301 } catch (\Exception $exception) {
304 $this->assertEquals("Endpoint value for \"{$endpointName}\" must start with https://", $err->getMessage());
306 config()->set($endpointConfigKey, $original);
310 public function test_auth_login_with_autodiscovery()
312 $this->withAutodiscovery();
314 $transactions = $this->mockHttpClient([
315 $this->getAutoDiscoveryResponse(),
316 $this->getJwksResponse(),
319 $this->assertFalse(auth()->check());
323 $this->assertTrue(auth()->check());
325 $discoverRequest = $transactions->requestAt(0);
326 $keysRequest = $transactions->requestAt(1);
327 $this->assertEquals('GET', $keysRequest->getMethod());
328 $this->assertEquals('GET', $discoverRequest->getMethod());
329 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/.well-known/openid-configuration', $discoverRequest->getUri());
330 $this->assertEquals(OidcJwtHelper::defaultIssuer() . '/oidc/keys', $keysRequest->getUri());
333 public function test_auth_fails_if_autodiscovery_fails()
335 $this->withAutodiscovery();
336 $this->mockHttpClient([
337 new Response(404, [], 'Not found'),
340 $resp = $this->followRedirects($this->runLogin());
341 $this->assertFalse(auth()->check());
342 $resp->assertSeeText('Login using SingleSignOn-Testing failed, system did not provide successful authorization');
345 public function test_autodiscovery_calls_are_cached()
347 $this->withAutodiscovery();
349 $transactions = $this->mockHttpClient([
350 $this->getAutoDiscoveryResponse(),
351 $this->getJwksResponse(),
352 $this->getAutoDiscoveryResponse([
353 'issuer' => 'https://auto.example.com',
355 $this->getJwksResponse(),
359 $this->post('/oidc/login');
360 $this->assertEquals(2, $transactions->requestCount());
361 // Second run, hits cache
362 $this->post('/oidc/login');
363 $this->assertEquals(2, $transactions->requestCount());
365 // Third run, different issuer, new cache key
366 config()->set(['oidc.issuer' => 'https://auto.example.com']);
367 $this->post('/oidc/login');
368 $this->assertEquals(4, $transactions->requestCount());
371 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_alg_property()
373 $this->withAutodiscovery();
375 $keyArray = OidcJwtHelper::publicJwkKeyArray();
376 unset($keyArray['alg']);
378 $this->mockHttpClient([
379 $this->getAutoDiscoveryResponse(),
381 'Content-Type' => 'application/json',
382 'Cache-Control' => 'no-cache, no-store',
383 'Pragma' => 'no-cache',
391 $this->assertFalse(auth()->check());
393 $this->assertTrue(auth()->check());
396 public function test_auth_login_with_autodiscovery_with_keys_that_do_not_have_use_property()
398 // Based on reading the OIDC discovery spec:
399 // > This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also
400 // > contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When
401 // > both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all
402 // > keys in the referenced JWK Set to indicate each key's intended usage.
403 // We can assume that keys without use are intended for signing.
404 $this->withAutodiscovery();
406 $keyArray = OidcJwtHelper::publicJwkKeyArray();
407 unset($keyArray['use']);
409 $this->mockHttpClient([
410 $this->getAutoDiscoveryResponse(),
412 'Content-Type' => 'application/json',
413 'Cache-Control' => 'no-cache, no-store',
414 'Pragma' => 'no-cache',
422 $this->assertFalse(auth()->check());
424 $this->assertTrue(auth()->check());
427 public function test_auth_uses_configured_external_id_claim_option()
430 'oidc.external_id_claim' => 'super_awesome_id',
433 $resp = $this->runLogin([
435 'sub' => 'benny1010101',
436 'super_awesome_id' => 'xXBennyTheGeezXx',
438 $resp->assertRedirect('/');
440 /** @var User $user */
442 $this->assertEquals('xXBennyTheGeezXx', $user->external_auth_id);
445 public function test_auth_uses_mulitple_display_name_claims_if_configured()
447 config()->set(['oidc.display_name_claims' => 'first_name|last_name']);
451 'sub' => 'benny1010101',
452 'first_name' => 'Benny',
453 'last_name' => 'Jenkins'
456 $this->assertDatabaseHas('users', [
457 'name' => 'Benny Jenkins',
462 public function test_user_avatar_fetched_from_picture_on_first_login_if_enabled()
464 config()->set(['oidc.fetch_avatar' => true]);
468 'picture' => 'https://example.com/my-avatar.jpg',
470 new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
474 $this->assertNotNull($user);
476 $this->assertTrue($user->avatar()->exists());
479 public function test_user_avatar_fetched_for_existing_user_when_no_avatar_already_assigned()
481 config()->set(['oidc.fetch_avatar' => true]);
482 $editor = $this->users->editor();
483 $editor->external_auth_id = 'benny509';
486 $this->assertFalse($editor->avatar()->exists());
489 'picture' => 'https://example.com/my-avatar.jpg',
492 new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
496 $this->assertTrue($editor->avatar()->exists());
499 public function test_user_avatar_not_fetched_if_image_data_format_unknown()
501 config()->set(['oidc.fetch_avatar' => true]);
505 'picture' => 'https://example.com/my-avatar.jpg',
507 new Response(200, ['Content-Type' => 'image/jpeg'], str_repeat('abc123', 5))
511 $this->assertNotNull($user);
513 $this->assertFalse($user->avatar()->exists());
516 public function test_user_avatar_not_fetched_when_avatar_already_assigned()
518 config()->set(['oidc.fetch_avatar' => true]);
519 $editor = $this->users->editor();
520 $editor->external_auth_id = 'benny509';
523 $avatars = $this->app->make(UserAvatars::class);
524 $originalImageData = $this->files->pngImageData();
525 $avatars->assignToUserFromExistingData($editor, $originalImageData, 'png');
528 'picture' => 'https://example.com/my-avatar.jpg',
531 new Response(200, ['Content-Type' => 'image/jpeg'], $this->files->jpegImageData())
535 $newAvatarData = file_get_contents($this->files->relativeToFullPath($editor->avatar->path));
536 $this->assertEquals($originalImageData, $newAvatarData);
539 public function test_user_avatar_fetch_follows_up_to_three_redirects()
541 config()->set(['oidc.fetch_avatar' => true]);
543 $logger = $this->withTestLogger();
547 'picture' => 'https://example.com/my-avatar.jpg',
549 new Response(302, ['Location' => 'https://example.com/a']),
550 new Response(302, ['Location' => 'https://example.com/b']),
551 new Response(302, ['Location' => 'https://example.com/c']),
552 new Response(302, ['Location' => 'https://example.com/d']),
556 $this->assertFalse($user->avatar()->exists());
558 $this->assertStringContainsString('"Failed to fetch image, max redirect limit of 3 tries reached. Last fetched URL: https://example.com/c"', $logger->getRecords()[0]->formatted);
561 public function test_login_group_sync()
564 'oidc.user_to_groups' => true,
565 'oidc.groups_claim' => 'groups',
566 'oidc.remove_from_groups' => false,
568 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
569 $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
570 $roleC = Role::factory()->create(['display_name' => 'Another Role']);
572 $resp = $this->runLogin([
574 'sub' => 'benny1010101',
575 'groups' => ['Wizards', 'Zookeepers'],
577 $resp->assertRedirect('/');
579 /** @var User $user */
582 $this->assertTrue($user->hasRole($roleA->id));
583 $this->assertTrue($user->hasRole($roleB->id));
584 $this->assertFalse($user->hasRole($roleC->id));
587 public function test_login_group_sync_with_nested_groups_in_token()
590 'oidc.user_to_groups' => true,
591 'oidc.groups_claim' => 'my.custom.groups.attr',
592 'oidc.remove_from_groups' => false,
594 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
596 $resp = $this->runLogin([
598 'sub' => 'benny1010101',
602 'attr' => ['Wizards'],
607 $resp->assertRedirect('/');
609 /** @var User $user */
611 $this->assertTrue($user->hasRole($roleA->id));
614 public function test_oidc_logout_form_active_when_oidc_active()
618 $resp = $this->get('/');
619 $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
621 public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
623 config()->set(['oidc.end_session_endpoint' => true]);
624 $this->withAutodiscovery();
626 $transactions = $this->mockHttpClient([
627 $this->getAutoDiscoveryResponse(),
628 $this->getJwksResponse(),
631 $resp = $this->asEditor()->post('/oidc/logout');
632 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
634 $this->assertEquals(2, $transactions->requestCount());
635 $this->assertFalse(auth()->check());
638 public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
640 $this->withAutodiscovery();
641 config()->set(['oidc.end_session_endpoint' => false]);
643 $this->mockHttpClient([
644 $this->getAutoDiscoveryResponse(),
645 $this->getJwksResponse(),
648 $resp = $this->asEditor()->post('/oidc/logout');
649 $resp->assertRedirect('/');
650 $this->assertFalse(auth()->check());
653 public function test_logout_without_autodiscovery_but_with_endpoint_configured()
655 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
657 $resp = $this->asEditor()->post('/oidc/logout');
658 $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
659 $this->assertFalse(auth()->check());
662 public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
664 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
666 $resp = $this->asEditor()->post('/oidc/logout');
667 $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
668 $this->assertFalse(auth()->check());
671 public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
673 $this->withAutodiscovery();
675 'auth.auto_initiate' => true,
676 'services.google.client_id' => false,
677 'services.github.client_id' => false,
678 'oidc.end_session_endpoint' => true,
681 $this->mockHttpClient([
682 $this->getAutoDiscoveryResponse(),
683 $this->getJwksResponse(),
686 $resp = $this->asEditor()->post('/oidc/logout');
688 $redirectUrl = url('/login?prevent_auto_init=true');
689 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
690 $this->assertFalse(auth()->check());
693 public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
695 config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
696 $this->withAutodiscovery();
698 $transactions = $this->mockHttpClient([
699 $this->getAutoDiscoveryResponse(),
700 $this->getJwksResponse(),
703 $resp = $this->asEditor()->post('/oidc/logout');
704 $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
706 $this->assertEquals(2, $transactions->requestCount());
707 $this->assertFalse(auth()->check());
710 public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
712 config()->set(['oidc.end_session_endpoint' => true]);
713 $this->withAutodiscovery();
715 $this->mockHttpClient([
716 $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
717 $this->getJwksResponse(),
720 $resp = $this->asEditor()->post('/oidc/logout');
721 $resp->assertRedirect('/');
722 $this->assertFalse(auth()->check());
725 public function test_logout_redirect_contains_id_token_hint_if_existing()
727 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
729 // Fix times so our token is predictable
732 'exp' => time() + 720,
733 'auth_time' => time()
735 $this->runLogin($claimOverrides);
737 $resp = $this->asEditor()->post('/oidc/logout');
738 $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) . '&post_logout_redirect_uri=' . urlencode(url('/'));
739 $resp->assertRedirect('https://example.com/logout?' . $query);
742 public function test_oidc_id_token_pre_validate_theme_event_without_return()
745 $callback = function (...$eventArgs) use (&$args) {
748 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
750 $resp = $this->runLogin([
752 'sub' => 'benny1010101',
755 $resp->assertRedirect('/');
757 $this->assertDatabaseHas('users', [
758 'external_auth_id' => 'benny1010101',
761 $this->assertArrayHasKey('iss', $args[0]);
762 $this->assertArrayHasKey('sub', $args[0]);
763 $this->assertEquals('Benny', $args[0]['name']);
764 $this->assertEquals('benny1010101', $args[0]['sub']);
766 $this->assertArrayHasKey('access_token', $args[1]);
767 $this->assertArrayHasKey('expires_in', $args[1]);
768 $this->assertArrayHasKey('refresh_token', $args[1]);
771 public function test_oidc_id_token_pre_validate_theme_event_with_return()
773 $callback = function (...$eventArgs) {
774 return array_merge($eventArgs[0], [
776 'sub' => 'lenny1010101',
780 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
782 $resp = $this->runLogin([
784 'sub' => 'benny1010101',
787 $resp->assertRedirect('/');
789 $this->assertDatabaseHas('users', [
791 'external_auth_id' => 'lenny1010101',
796 public function test_pkce_used_on_authorize_and_access()
799 $resp = $this->post('/oidc/login');
800 $state = session()->get('oidc_state');
802 $pkceCode = session()->get('oidc_pkce_code');
803 $this->assertGreaterThan(30, strlen($pkceCode));
805 $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
806 $redirect = $resp->headers->get('Location');
807 $redirectParams = [];
808 parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
809 $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
810 $this->assertEquals('S256', $redirectParams['code_challenge_method']);
812 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
814 'sub' => 'benny1010101',
817 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
818 $tokenRequest = $transactions->latestRequest();
820 parse_str($tokenRequest->getBody(), $bodyParams);
821 $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
824 public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
826 config()->set('oidc.display_name_claims', 'first_name|last_name');
827 $this->post('/oidc/login');
828 $state = session()->get('oidc_state');
830 $client = $this->mockHttpClient([
831 $this->getMockAuthorizationResponse(['name' => null]),
833 'Content-Type' => 'application/json',
835 'sub' => OidcJwtHelper::defaultPayload()['sub'],
836 'first_name' => 'Barry',
837 'last_name' => 'Userinfo',
841 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
842 $resp->assertRedirect('/');
843 $this->assertEquals(2, $client->requestCount());
845 $userinfoRequest = $client->requestAt(1);
846 $this->assertEquals('GET', $userinfoRequest->getMethod());
847 $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
849 $this->assertEquals('Barry Userinfo', user()->name);
852 public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
854 $userinfoResponseData = ['sub' => 'dcba4321'];
855 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
856 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
857 $resp->assertRedirect('/login');
858 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
861 public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
863 $userinfoResponseData = ['name' => 'testing'];
864 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
865 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
866 $resp->assertRedirect('/login');
867 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
870 public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
873 'oidc.user_to_groups' => true,
874 'oidc.groups_claim' => 'my.nested.groups.attr',
875 'oidc.remove_from_groups' => false,
878 $roleA = Role::factory()->create(['display_name' => 'Ducks']);
879 $userinfoResponseData = [
880 'sub' => OidcJwtHelper::defaultPayload()['sub'],
881 'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
883 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
884 $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
885 $resp->assertRedirect('/');
887 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
888 $this->assertTrue($user->hasRole($roleA->id));
891 public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
893 $userinfoResponseData = [
894 'sub' => OidcJwtHelper::defaultPayload()['sub'],
897 $userinfoResponse = new Response(200, ['Content-Type' => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
898 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
899 $resp->assertRedirect('/');
901 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
902 $this->assertEquals('Barry', $user->name);
905 public function test_userinfo_endpoint_jwks_response_handled()
907 $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
908 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
910 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
911 $resp->assertRedirect('/');
913 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
914 $this->assertEquals('Barry Jwks', $user->name);
917 public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
919 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
920 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
922 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
923 $resp->assertRedirect('/login');
924 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
927 public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
929 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
930 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
932 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
933 $resp->assertRedirect('/login');
934 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
937 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
939 $userinfoResponseData = OidcJwtHelper::idToken();
940 $exploded = explode('.', $userinfoResponseData);
941 $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
942 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], implode('.', $exploded));
944 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
945 $resp->assertRedirect('/login');
946 $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
949 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
951 $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
952 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
954 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
955 $resp->assertRedirect('/login');
956 $this->assertSessionError('Userinfo endpoint response validation failed with error: Only RS256 signature validation is supported. Token reports using ZZ512');
959 public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
961 $userinfoResponse = new Response(200, ['Content-Type' => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
962 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
963 $resp->assertRedirect('/login');
964 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
967 public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
970 'oidc.user_to_groups' => true,
971 'oidc.groups_claim' => 'groups',
972 'oidc.remove_from_groups' => false,
975 $this->post('/oidc/login');
976 $state = session()->get('oidc_state');
977 $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
981 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
982 $resp->assertRedirect('/');
983 $this->assertEquals(1, $client->requestCount());
984 $this->assertTrue(auth()->check());
987 protected function withAutodiscovery(): void
990 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
991 'oidc.discover' => true,
992 'oidc.authorization_endpoint' => null,
993 'oidc.token_endpoint' => null,
994 'oidc.userinfo_endpoint' => null,
995 'oidc.jwt_public_key' => null,
999 protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
1001 $this->post('/oidc/login');
1002 $state = session()->get('oidc_state');
1003 $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
1005 return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
1008 protected function getAutoDiscoveryResponse($responseOverrides = []): Response
1010 return new Response(200, [
1011 'Content-Type' => 'application/json',
1012 'Cache-Control' => 'no-cache, no-store',
1013 'Pragma' => 'no-cache',
1014 ], json_encode(array_merge([
1015 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
1016 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
1017 'userinfo_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
1018 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
1019 'issuer' => OidcJwtHelper::defaultIssuer(),
1020 'end_session_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
1021 ], $responseOverrides)));
1024 protected function getJwksResponse(): Response
1026 return new Response(200, [
1027 'Content-Type' => 'application/json',
1028 'Cache-Control' => 'no-cache, no-store',
1029 'Pragma' => 'no-cache',
1032 OidcJwtHelper::publicJwkKeyArray(),
1037 protected function getMockAuthorizationResponse($claimOverrides = []): Response
1039 return new Response(200, [
1040 'Content-Type' => 'application/json',
1041 'Cache-Control' => 'no-cache, no-store',
1042 'Pragma' => 'no-cache',
1044 'access_token' => 'abc123',
1045 'token_type' => 'Bearer',
1046 'expires_in' => 3600,
1047 'id_token' => OidcJwtHelper::idToken($claimOverrides),