3 namespace BookStack\Access\Oidc;
5 use BookStack\Access\GroupSyncService;
6 use BookStack\Access\LoginService;
7 use BookStack\Access\RegistrationService;
8 use BookStack\Exceptions\JsonDebugException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Facades\Theme;
12 use BookStack\Http\HttpRequestService;
13 use BookStack\Theming\ThemeEvents;
14 use BookStack\Users\Models\User;
15 use Illuminate\Support\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
20 * Class OpenIdConnectService
21 * Handles any app-specific OIDC tasks.
25 public function __construct(
26 protected RegistrationService $registrationService,
27 protected LoginService $loginService,
28 protected HttpRequestService $http,
29 protected GroupSyncService $groupService
34 * Initiate an authorization flow.
35 * Provides back an authorize redirect URL, in addition to other
36 * details which may be required for the auth flow.
38 * @throws OidcException
40 * @return array{url: string, state: string}
42 public function login(): array
44 $settings = $this->getProviderSettings();
45 $provider = $this->getProvider($settings);
47 $url = $provider->getAuthorizationUrl();
48 session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
52 'state' => $provider->getState(),
57 * Process the Authorization response from the authorization server and
58 * return the matching, or new if registration active, user matched to the
59 * authorization server. Throws if the user cannot be auth if not authenticated.
61 * @throws JsonDebugException
62 * @throws OidcException
63 * @throws StoppedAuthenticationException
64 * @throws IdentityProviderException
66 public function processAuthorizeResponse(?string $authorizationCode): User
68 $settings = $this->getProviderSettings();
69 $provider = $this->getProvider($settings);
71 // Set PKCE code flashed at login
72 $pkceCode = session()->pull('oidc_pkce_code', '');
73 $provider->setPkceCode($pkceCode);
75 // Try to exchange authorization code for access token
76 $accessToken = $provider->getAccessToken('authorization_code', [
77 'code' => $authorizationCode,
80 return $this->processAccessTokenCallback($accessToken, $settings);
84 * @throws OidcException
86 protected function getProviderSettings(): OidcProviderSettings
88 $config = $this->config();
89 $settings = new OidcProviderSettings([
90 'issuer' => $config['issuer'],
91 'clientId' => $config['client_id'],
92 'clientSecret' => $config['client_secret'],
93 'authorizationEndpoint' => $config['authorization_endpoint'],
94 'tokenEndpoint' => $config['token_endpoint'],
95 'endSessionEndpoint' => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
96 'userinfoEndpoint' => $config['userinfo_endpoint'],
99 // Use keys if configured
100 if (!empty($config['jwt_public_key'])) {
101 $settings->keys = [$config['jwt_public_key']];
105 if ($config['discover'] ?? false) {
107 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
108 } catch (OidcIssuerDiscoveryException $exception) {
109 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
113 // Prevent use of RP-initiated logout if specifically disabled
114 // Or force use of a URL if specifically set.
115 if ($config['end_session_endpoint'] === false) {
116 $settings->endSessionEndpoint = null;
117 } else if (is_string($config['end_session_endpoint'])) {
118 $settings->endSessionEndpoint = $config['end_session_endpoint'];
121 $settings->validate();
127 * Load the underlying OpenID Connect Provider.
129 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
131 $provider = new OidcOAuthProvider([
132 ...$settings->arrayForOAuthProvider(),
133 'redirectUri' => url('/oidc/callback'),
135 'httpClient' => $this->http->buildClient(5),
136 'optionProvider' => new HttpBasicAuthOptionProvider(),
139 foreach ($this->getAdditionalScopes() as $scope) {
140 $provider->addScope($scope);
147 * Get any user-defined addition/custom scopes to apply to the authentication request.
151 protected function getAdditionalScopes(): array
153 $scopeConfig = $this->config()['additional_scopes'] ?: '';
155 $scopeArr = explode(',', $scopeConfig);
156 $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
158 return array_filter($scopeArr);
162 * Processes a received access token for a user. Login the user when
163 * they exist, optionally registering them automatically.
165 * @throws OidcException
166 * @throws JsonDebugException
167 * @throws StoppedAuthenticationException
169 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
171 $idTokenText = $accessToken->getIdToken();
172 $idToken = new OidcIdToken(
178 session()->put("oidc_id_token", $idTokenText);
180 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
181 'access_token' => $accessToken->getToken(),
182 'expires_in' => $accessToken->getExpires(),
183 'refresh_token' => $accessToken->getRefreshToken(),
186 if (!is_null($returnClaims)) {
187 $idToken->replaceClaims($returnClaims);
190 if ($this->config()['dump_user_details']) {
191 throw new JsonDebugException($idToken->getAllClaims());
195 $idToken->validate($settings->clientId);
196 } catch (OidcInvalidTokenException $exception) {
197 throw new OidcException("ID token validation failed with error: {$exception->getMessage()}");
200 $userDetails = $this->getUserDetailsFromToken($idToken, $accessToken, $settings);
201 if (empty($userDetails->email)) {
202 throw new OidcException(trans('errors.oidc_no_email_address'));
204 if (empty($userDetails->name)) {
205 $userDetails->name = $userDetails->externalId;
208 $isLoggedIn = auth()->check();
210 throw new OidcException(trans('errors.oidc_already_logged_in'));
214 $user = $this->registrationService->findOrRegister(
217 $userDetails->externalId
219 } catch (UserRegistrationException $exception) {
220 throw new OidcException($exception->getMessage());
223 if ($this->shouldSyncGroups()) {
224 $detachExisting = $this->config()['remove_from_groups'];
225 $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
228 $this->loginService->login($user, 'oidc');
234 * @throws OidcException
236 protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
238 $userDetails = new OidcUserDetails();
239 $userDetails->populate(
241 $this->config()['external_id_claim'],
242 $this->config()['display_name_claims'] ?? '',
243 $this->config()['groups_claim'] ?? ''
246 if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
247 $provider = $this->getProvider($settings);
248 $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
249 $response = new OidcUserinfoResponse(
250 $provider->getResponse($request),
256 $response->validate($idToken->getClaim('sub'), $settings->clientId);
257 } catch (OidcInvalidTokenException $exception) {
258 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
261 $userDetails->populate(
263 $this->config()['external_id_claim'],
264 $this->config()['display_name_claims'] ?? '',
265 $this->config()['groups_claim'] ?? ''
273 * Get the OIDC config from the application.
275 protected function config(): array
277 return config('oidc');
281 * Check if groups should be synced.
283 protected function shouldSyncGroups(): bool
285 return $this->config()['user_to_groups'] !== false;
289 * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
290 * Returns a post-app-logout redirect URL.
291 * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
292 * @throws OidcException
294 public function logout(): string
296 $oidcToken = session()->pull("oidc_id_token");
297 $defaultLogoutUrl = url($this->loginService->logout());
298 $oidcSettings = $this->getProviderSettings();
300 if (!$oidcSettings->endSessionEndpoint) {
301 return $defaultLogoutUrl;
305 'id_token_hint' => $oidcToken,
306 'post_logout_redirect_uri' => $defaultLogoutUrl,
309 $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
311 return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);