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_login_group_sync()
542 'oidc.user_to_groups' => true,
543 'oidc.groups_claim' => 'groups',
544 'oidc.remove_from_groups' => false,
546 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
547 $roleB = Role::factory()->create(['display_name' => 'ZooFolks', 'external_auth_id' => 'zookeepers']);
548 $roleC = Role::factory()->create(['display_name' => 'Another Role']);
550 $resp = $this->runLogin([
552 'sub' => 'benny1010101',
553 'groups' => ['Wizards', 'Zookeepers'],
555 $resp->assertRedirect('/');
557 /** @var User $user */
560 $this->assertTrue($user->hasRole($roleA->id));
561 $this->assertTrue($user->hasRole($roleB->id));
562 $this->assertFalse($user->hasRole($roleC->id));
565 public function test_login_group_sync_with_nested_groups_in_token()
568 'oidc.user_to_groups' => true,
569 'oidc.groups_claim' => 'my.custom.groups.attr',
570 'oidc.remove_from_groups' => false,
572 $roleA = Role::factory()->create(['display_name' => 'Wizards']);
574 $resp = $this->runLogin([
576 'sub' => 'benny1010101',
580 'attr' => ['Wizards'],
585 $resp->assertRedirect('/');
587 /** @var User $user */
589 $this->assertTrue($user->hasRole($roleA->id));
592 public function test_oidc_logout_form_active_when_oidc_active()
596 $resp = $this->get('/');
597 $this->withHtml($resp)->assertElementExists('header form[action$="/oidc/logout"] button');
599 public function test_logout_with_autodiscovery_with_oidc_logout_enabled()
601 config()->set(['oidc.end_session_endpoint' => true]);
602 $this->withAutodiscovery();
604 $transactions = $this->mockHttpClient([
605 $this->getAutoDiscoveryResponse(),
606 $this->getJwksResponse(),
609 $resp = $this->asEditor()->post('/oidc/logout');
610 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode(url('/')));
612 $this->assertEquals(2, $transactions->requestCount());
613 $this->assertFalse(auth()->check());
616 public function test_logout_with_autodiscovery_with_oidc_logout_disabled()
618 $this->withAutodiscovery();
619 config()->set(['oidc.end_session_endpoint' => false]);
621 $this->mockHttpClient([
622 $this->getAutoDiscoveryResponse(),
623 $this->getJwksResponse(),
626 $resp = $this->asEditor()->post('/oidc/logout');
627 $resp->assertRedirect('/');
628 $this->assertFalse(auth()->check());
631 public function test_logout_without_autodiscovery_but_with_endpoint_configured()
633 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
635 $resp = $this->asEditor()->post('/oidc/logout');
636 $resp->assertRedirect('https://example.com/logout?post_logout_redirect_uri=' . urlencode(url('/')));
637 $this->assertFalse(auth()->check());
640 public function test_logout_without_autodiscovery_with_configured_endpoint_adds_to_query_if_existing()
642 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout?a=b']);
644 $resp = $this->asEditor()->post('/oidc/logout');
645 $resp->assertRedirect('https://example.com/logout?a=b&post_logout_redirect_uri=' . urlencode(url('/')));
646 $this->assertFalse(auth()->check());
649 public function test_logout_with_autodiscovery_and_auto_initiate_returns_to_auto_prevented_login()
651 $this->withAutodiscovery();
653 'auth.auto_initiate' => true,
654 'services.google.client_id' => false,
655 'services.github.client_id' => false,
656 'oidc.end_session_endpoint' => true,
659 $this->mockHttpClient([
660 $this->getAutoDiscoveryResponse(),
661 $this->getJwksResponse(),
664 $resp = $this->asEditor()->post('/oidc/logout');
666 $redirectUrl = url('/login?prevent_auto_init=true');
667 $resp->assertRedirect('https://auth.example.com/oidc/logout?post_logout_redirect_uri=' . urlencode($redirectUrl));
668 $this->assertFalse(auth()->check());
671 public function test_logout_endpoint_url_overrides_autodiscovery_endpoint()
673 config()->set(['oidc.end_session_endpoint' => 'https://a.example.com']);
674 $this->withAutodiscovery();
676 $transactions = $this->mockHttpClient([
677 $this->getAutoDiscoveryResponse(),
678 $this->getJwksResponse(),
681 $resp = $this->asEditor()->post('/oidc/logout');
682 $resp->assertRedirect('https://a.example.com?post_logout_redirect_uri=' . urlencode(url('/')));
684 $this->assertEquals(2, $transactions->requestCount());
685 $this->assertFalse(auth()->check());
688 public function test_logout_with_autodiscovery_does_not_use_rp_logout_if_no_url_via_autodiscovery()
690 config()->set(['oidc.end_session_endpoint' => true]);
691 $this->withAutodiscovery();
693 $this->mockHttpClient([
694 $this->getAutoDiscoveryResponse(['end_session_endpoint' => null]),
695 $this->getJwksResponse(),
698 $resp = $this->asEditor()->post('/oidc/logout');
699 $resp->assertRedirect('/');
700 $this->assertFalse(auth()->check());
703 public function test_logout_redirect_contains_id_token_hint_if_existing()
705 config()->set(['oidc.end_session_endpoint' => 'https://example.com/logout']);
707 // Fix times so our token is predictable
710 'exp' => time() + 720,
711 'auth_time' => time()
713 $this->runLogin($claimOverrides);
715 $resp = $this->asEditor()->post('/oidc/logout');
716 $query = 'id_token_hint=' . urlencode(OidcJwtHelper::idToken($claimOverrides)) . '&post_logout_redirect_uri=' . urlencode(url('/'));
717 $resp->assertRedirect('https://example.com/logout?' . $query);
720 public function test_oidc_id_token_pre_validate_theme_event_without_return()
723 $callback = function (...$eventArgs) use (&$args) {
726 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
728 $resp = $this->runLogin([
730 'sub' => 'benny1010101',
733 $resp->assertRedirect('/');
735 $this->assertDatabaseHas('users', [
736 'external_auth_id' => 'benny1010101',
739 $this->assertArrayHasKey('iss', $args[0]);
740 $this->assertArrayHasKey('sub', $args[0]);
741 $this->assertEquals('Benny', $args[0]['name']);
742 $this->assertEquals('benny1010101', $args[0]['sub']);
744 $this->assertArrayHasKey('access_token', $args[1]);
745 $this->assertArrayHasKey('expires_in', $args[1]);
746 $this->assertArrayHasKey('refresh_token', $args[1]);
749 public function test_oidc_id_token_pre_validate_theme_event_with_return()
751 $callback = function (...$eventArgs) {
752 return array_merge($eventArgs[0], [
754 'sub' => 'lenny1010101',
758 Theme::listen(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $callback);
760 $resp = $this->runLogin([
762 'sub' => 'benny1010101',
765 $resp->assertRedirect('/');
767 $this->assertDatabaseHas('users', [
769 'external_auth_id' => 'lenny1010101',
774 public function test_pkce_used_on_authorize_and_access()
777 $resp = $this->post('/oidc/login');
778 $state = session()->get('oidc_state');
780 $pkceCode = session()->get('oidc_pkce_code');
781 $this->assertGreaterThan(30, strlen($pkceCode));
783 $expectedCodeChallenge = trim(strtr(base64_encode(hash('sha256', $pkceCode, true)), '+/', '-_'), '=');
784 $redirect = $resp->headers->get('Location');
785 $redirectParams = [];
786 parse_str(parse_url($redirect, PHP_URL_QUERY), $redirectParams);
787 $this->assertEquals($expectedCodeChallenge, $redirectParams['code_challenge']);
788 $this->assertEquals('S256', $redirectParams['code_challenge_method']);
790 $transactions = $this->mockHttpClient([$this->getMockAuthorizationResponse([
792 'sub' => 'benny1010101',
795 $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
796 $tokenRequest = $transactions->latestRequest();
798 parse_str($tokenRequest->getBody(), $bodyParams);
799 $this->assertEquals($pkceCode, $bodyParams['code_verifier']);
802 public function test_userinfo_endpoint_used_if_missing_claims_in_id_token()
804 config()->set('oidc.display_name_claims', 'first_name|last_name');
805 $this->post('/oidc/login');
806 $state = session()->get('oidc_state');
808 $client = $this->mockHttpClient([
809 $this->getMockAuthorizationResponse(['name' => null]),
811 'Content-Type' => 'application/json',
813 'sub' => OidcJwtHelper::defaultPayload()['sub'],
814 'first_name' => 'Barry',
815 'last_name' => 'Userinfo',
819 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
820 $resp->assertRedirect('/');
821 $this->assertEquals(2, $client->requestCount());
823 $userinfoRequest = $client->requestAt(1);
824 $this->assertEquals('GET', $userinfoRequest->getMethod());
825 $this->assertEquals('https://oidc.local/userinfo', (string) $userinfoRequest->getUri());
827 $this->assertEquals('Barry Userinfo', user()->name);
830 public function test_userinfo_endpoint_fetch_with_different_sub_throws_error()
832 $userinfoResponseData = ['sub' => 'dcba4321'];
833 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
834 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
835 $resp->assertRedirect('/login');
836 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
839 public function test_userinfo_endpoint_fetch_returning_no_sub_throws_error()
841 $userinfoResponseData = ['name' => 'testing'];
842 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
843 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
844 $resp->assertRedirect('/login');
845 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
848 public function test_userinfo_endpoint_fetch_can_parsed_nested_groups()
851 'oidc.user_to_groups' => true,
852 'oidc.groups_claim' => 'my.nested.groups.attr',
853 'oidc.remove_from_groups' => false,
856 $roleA = Role::factory()->create(['display_name' => 'Ducks']);
857 $userinfoResponseData = [
858 'sub' => OidcJwtHelper::defaultPayload()['sub'],
859 'my' => ['nested' => ['groups' => ['attr' => ['Ducks', 'Donkeys']]]]
861 $userinfoResponse = new Response(200, ['Content-Type' => 'application/json'], json_encode($userinfoResponseData));
862 $resp = $this->runLogin(['groups' => null], [$userinfoResponse]);
863 $resp->assertRedirect('/');
865 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
866 $this->assertTrue($user->hasRole($roleA->id));
869 public function test_userinfo_endpoint_response_with_complex_json_content_type_handled()
871 $userinfoResponseData = [
872 'sub' => OidcJwtHelper::defaultPayload()['sub'],
875 $userinfoResponse = new Response(200, ['Content-Type' => 'Application/Json ; charset=utf-8'], json_encode($userinfoResponseData));
876 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
877 $resp->assertRedirect('/');
879 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
880 $this->assertEquals('Barry', $user->name);
883 public function test_userinfo_endpoint_jwks_response_handled()
885 $userinfoResponseData = OidcJwtHelper::idToken(['name' => 'Barry Jwks']);
886 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
888 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
889 $resp->assertRedirect('/');
891 $user = User::where('email', OidcJwtHelper::defaultPayload()['email'])->first();
892 $this->assertEquals('Barry Jwks', $user->name);
895 public function test_userinfo_endpoint_jwks_response_returning_no_sub_throws()
897 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => null]);
898 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
900 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
901 $resp->assertRedirect('/login');
902 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
905 public function test_userinfo_endpoint_jwks_response_returning_non_matching_sub_throws()
907 $userinfoResponseData = OidcJwtHelper::idToken(['sub' => 'zzz123']);
908 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], $userinfoResponseData);
910 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
911 $resp->assertRedirect('/login');
912 $this->assertSessionError('Userinfo endpoint response validation failed with error: Subject value provided in the userinfo endpoint does not match the provided ID token value');
915 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_throws()
917 $userinfoResponseData = OidcJwtHelper::idToken();
918 $exploded = explode('.', $userinfoResponseData);
919 $exploded[2] = base64_encode(base64_decode($exploded[2]) . 'ABC');
920 $userinfoResponse = new Response(200, ['Content-Type' => 'application/jwt'], implode('.', $exploded));
922 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
923 $resp->assertRedirect('/login');
924 $this->assertSessionError('Userinfo endpoint response validation failed with error: Token signature could not be validated using the provided keys');
927 public function test_userinfo_endpoint_jwks_response_with_invalid_signature_alg_throws()
929 $userinfoResponseData = OidcJwtHelper::idToken([], ['alg' => 'ZZ512']);
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: Only RS256 signature validation is supported. Token reports using ZZ512');
937 public function test_userinfo_endpoint_response_with_invalid_content_type_throws()
939 $userinfoResponse = new Response(200, ['Content-Type' => 'application/beans'], json_encode(OidcJwtHelper::defaultPayload()));
940 $resp = $this->runLogin(['name' => null], [$userinfoResponse]);
941 $resp->assertRedirect('/login');
942 $this->assertSessionError('Userinfo endpoint response validation failed with error: No valid subject value found in userinfo data');
945 public function test_userinfo_endpoint_not_called_if_empty_groups_array_provided_in_id_token()
948 'oidc.user_to_groups' => true,
949 'oidc.groups_claim' => 'groups',
950 'oidc.remove_from_groups' => false,
953 $this->post('/oidc/login');
954 $state = session()->get('oidc_state');
955 $client = $this->mockHttpClient([$this->getMockAuthorizationResponse([
959 $resp = $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
960 $resp->assertRedirect('/');
961 $this->assertEquals(1, $client->requestCount());
962 $this->assertTrue(auth()->check());
965 protected function withAutodiscovery(): void
968 'oidc.issuer' => OidcJwtHelper::defaultIssuer(),
969 'oidc.discover' => true,
970 'oidc.authorization_endpoint' => null,
971 'oidc.token_endpoint' => null,
972 'oidc.userinfo_endpoint' => null,
973 'oidc.jwt_public_key' => null,
977 protected function runLogin($claimOverrides = [], $additionalHttpResponses = []): TestResponse
979 $this->post('/oidc/login');
980 $state = session()->get('oidc_state');
981 $this->mockHttpClient([$this->getMockAuthorizationResponse($claimOverrides), ...$additionalHttpResponses]);
983 return $this->get('/oidc/callback?code=SplxlOBeZQQYbYS6WxSbIA&state=' . $state);
986 protected function getAutoDiscoveryResponse($responseOverrides = []): Response
988 return new Response(200, [
989 'Content-Type' => 'application/json',
990 'Cache-Control' => 'no-cache, no-store',
991 'Pragma' => 'no-cache',
992 ], json_encode(array_merge([
993 'token_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/token',
994 'authorization_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/authorize',
995 'userinfo_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/userinfo',
996 'jwks_uri' => OidcJwtHelper::defaultIssuer() . '/oidc/keys',
997 'issuer' => OidcJwtHelper::defaultIssuer(),
998 'end_session_endpoint' => OidcJwtHelper::defaultIssuer() . '/oidc/logout',
999 ], $responseOverrides)));
1002 protected function getJwksResponse(): Response
1004 return new Response(200, [
1005 'Content-Type' => 'application/json',
1006 'Cache-Control' => 'no-cache, no-store',
1007 'Pragma' => 'no-cache',
1010 OidcJwtHelper::publicJwkKeyArray(),
1015 protected function getMockAuthorizationResponse($claimOverrides = []): Response
1017 return new Response(200, [
1018 'Content-Type' => 'application/json',
1019 'Cache-Control' => 'no-cache, no-store',
1020 'Pragma' => 'no-cache',
1022 'access_token' => 'abc123',
1023 'token_type' => 'Bearer',
1024 'expires_in' => 3600,
1025 'id_token' => OidcJwtHelper::idToken($claimOverrides),