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\Uploads\UserAvatars;
15 use BookStack\Users\Models\User;
16 use Illuminate\Support\Facades\Cache;
17 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
18 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
21 * Class OpenIdConnectService
22 * Handles any app-specific OIDC tasks.
26 public function __construct(
27 protected RegistrationService $registrationService,
28 protected LoginService $loginService,
29 protected HttpRequestService $http,
30 protected GroupSyncService $groupService,
31 protected UserAvatars $userAvatars
36 * Initiate an authorization flow.
37 * Provides back an authorize redirect URL, in addition to other
38 * details which may be required for the auth flow.
40 * @throws OidcException
42 * @return array{url: string, state: string}
44 public function login(): array
46 $settings = $this->getProviderSettings();
47 $provider = $this->getProvider($settings);
49 $url = $provider->getAuthorizationUrl();
50 session()->put('oidc_pkce_code', $provider->getPkceCode() ?? '');
54 'state' => $provider->getState(),
59 * Process the Authorization response from the authorization server and
60 * return the matching, or new if registration active, user matched to the
61 * authorization server. Throws if the user cannot be auth if not authenticated.
63 * @throws JsonDebugException
64 * @throws OidcException
65 * @throws StoppedAuthenticationException
66 * @throws IdentityProviderException
68 public function processAuthorizeResponse(?string $authorizationCode): User
70 $settings = $this->getProviderSettings();
71 $provider = $this->getProvider($settings);
73 // Set PKCE code flashed at login
74 $pkceCode = session()->pull('oidc_pkce_code', '');
75 $provider->setPkceCode($pkceCode);
77 // Try to exchange authorization code for access token
78 $accessToken = $provider->getAccessToken('authorization_code', [
79 'code' => $authorizationCode,
82 return $this->processAccessTokenCallback($accessToken, $settings);
86 * @throws OidcException
88 protected function getProviderSettings(): OidcProviderSettings
90 $config = $this->config();
91 $settings = new OidcProviderSettings([
92 'issuer' => $config['issuer'],
93 'clientId' => $config['client_id'],
94 'clientSecret' => $config['client_secret'],
95 'authorizationEndpoint' => $config['authorization_endpoint'],
96 'tokenEndpoint' => $config['token_endpoint'],
97 'endSessionEndpoint' => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
98 'userinfoEndpoint' => $config['userinfo_endpoint'],
101 // Use keys if configured
102 if (!empty($config['jwt_public_key'])) {
103 $settings->keys = [$config['jwt_public_key']];
107 if ($config['discover'] ?? false) {
109 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
110 } catch (OidcIssuerDiscoveryException $exception) {
111 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
115 // Prevent use of RP-initiated logout if specifically disabled
116 // Or force use of a URL if specifically set.
117 if ($config['end_session_endpoint'] === false) {
118 $settings->endSessionEndpoint = null;
119 } else if (is_string($config['end_session_endpoint'])) {
120 $settings->endSessionEndpoint = $config['end_session_endpoint'];
123 $settings->validate();
129 * Load the underlying OpenID Connect Provider.
131 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
133 $provider = new OidcOAuthProvider([
134 ...$settings->arrayForOAuthProvider(),
135 'redirectUri' => url('/oidc/callback'),
137 'httpClient' => $this->http->buildClient(5),
138 'optionProvider' => new HttpBasicAuthOptionProvider(),
141 foreach ($this->getAdditionalScopes() as $scope) {
142 $provider->addScope($scope);
149 * Get any user-defined addition/custom scopes to apply to the authentication request.
153 protected function getAdditionalScopes(): array
155 $scopeConfig = $this->config()['additional_scopes'] ?: '';
157 $scopeArr = explode(',', $scopeConfig);
158 $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
160 return array_filter($scopeArr);
164 * Processes a received access token for a user. Login the user when
165 * they exist, optionally registering them automatically.
167 * @throws OidcException
168 * @throws JsonDebugException
169 * @throws StoppedAuthenticationException
171 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
173 $idTokenText = $accessToken->getIdToken();
174 $idToken = new OidcIdToken(
180 session()->put("oidc_id_token", $idTokenText);
182 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
183 'access_token' => $accessToken->getToken(),
184 'expires_in' => $accessToken->getExpires(),
185 'refresh_token' => $accessToken->getRefreshToken(),
188 if (!is_null($returnClaims)) {
189 $idToken->replaceClaims($returnClaims);
192 if ($this->config()['dump_user_details']) {
193 throw new JsonDebugException($idToken->getAllClaims());
197 $idToken->validate($settings->clientId);
198 } catch (OidcInvalidTokenException $exception) {
199 throw new OidcException("ID token validation failed with error: {$exception->getMessage()}");
202 $userDetails = $this->getUserDetailsFromToken($idToken, $accessToken, $settings);
203 if (empty($userDetails->email)) {
204 throw new OidcException(trans('errors.oidc_no_email_address'));
206 if (empty($userDetails->name)) {
207 $userDetails->name = $userDetails->externalId;
210 $isLoggedIn = auth()->check();
212 throw new OidcException(trans('errors.oidc_already_logged_in'));
216 $user = $this->registrationService->findOrRegister(
219 $userDetails->externalId
221 } catch (UserRegistrationException $exception) {
222 throw new OidcException($exception->getMessage());
225 // TODO - Update this (and tests and config option comments) to actually align with LDAP system
226 // which syncs whenever on login or registration, where there's no existing avatar.
227 if ($this->config()['fetch_avatar'] && $user->wasRecentlyCreated && $userDetails->picture) {
228 $this->userAvatars->assignToUserFromUrl($user, $userDetails->picture);
231 if ($this->shouldSyncGroups()) {
232 $detachExisting = $this->config()['remove_from_groups'];
233 $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
236 $this->loginService->login($user, 'oidc');
242 * @throws OidcException
244 protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
246 $userDetails = new OidcUserDetails();
247 $userDetails->populate(
249 $this->config()['external_id_claim'],
250 $this->config()['display_name_claims'] ?? '',
251 $this->config()['groups_claim'] ?? ''
254 if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
255 $provider = $this->getProvider($settings);
256 $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
257 $response = new OidcUserinfoResponse(
258 $provider->getResponse($request),
264 $response->validate($idToken->getClaim('sub'), $settings->clientId);
265 } catch (OidcInvalidTokenException $exception) {
266 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
269 $userDetails->populate(
271 $this->config()['external_id_claim'],
272 $this->config()['display_name_claims'] ?? '',
273 $this->config()['groups_claim'] ?? ''
281 * Get the OIDC config from the application.
283 protected function config(): array
285 return config('oidc');
289 * Check if groups should be synced.
291 protected function shouldSyncGroups(): bool
293 return $this->config()['user_to_groups'] !== false;
297 * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
298 * Returns a post-app-logout redirect URL.
299 * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
300 * @throws OidcException
302 public function logout(): string
304 $oidcToken = session()->pull("oidc_id_token");
305 $defaultLogoutUrl = url($this->loginService->logout());
306 $oidcSettings = $this->getProviderSettings();
308 if (!$oidcSettings->endSessionEndpoint) {
309 return $defaultLogoutUrl;
313 'id_token_hint' => $oidcToken,
314 'post_logout_redirect_uri' => $defaultLogoutUrl,
317 $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
319 return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);