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\Arr;
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
35 * Initiate an authorization flow.
37 * @throws OidcException
39 * @return array{url: string, state: string}
41 public function login(): array
43 $settings = $this->getProviderSettings();
44 $provider = $this->getProvider($settings);
46 'url' => $provider->getAuthorizationUrl(),
47 'state' => $provider->getState(),
52 * Process the Authorization response from the authorization server and
53 * return the matching, or new if registration active, user matched to the
54 * authorization server. Throws if the user cannot be auth if not authenticated.
56 * @throws JsonDebugException
57 * @throws OidcException
58 * @throws StoppedAuthenticationException
59 * @throws IdentityProviderException
61 public function processAuthorizeResponse(?string $authorizationCode): User
63 $settings = $this->getProviderSettings();
64 $provider = $this->getProvider($settings);
66 // Try to exchange authorization code for access token
67 $accessToken = $provider->getAccessToken('authorization_code', [
68 'code' => $authorizationCode,
71 return $this->processAccessTokenCallback($accessToken, $settings);
75 * @throws OidcException
77 protected function getProviderSettings(): OidcProviderSettings
79 $config = $this->config();
80 $settings = new OidcProviderSettings([
81 'issuer' => $config['issuer'],
82 'clientId' => $config['client_id'],
83 'clientSecret' => $config['client_secret'],
84 'redirectUri' => url('/oidc/callback'),
85 'authorizationEndpoint' => $config['authorization_endpoint'],
86 'tokenEndpoint' => $config['token_endpoint'],
87 'endSessionEndpoint' => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
90 // Use keys if configured
91 if (!empty($config['jwt_public_key'])) {
92 $settings->keys = [$config['jwt_public_key']];
96 if ($config['discover'] ?? false) {
98 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
99 } catch (OidcIssuerDiscoveryException $exception) {
100 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
104 // Prevent use of RP-initiated logout if specifically disabled
105 // Or force use of a URL if specifically set.
106 if ($config['end_session_endpoint'] === false) {
107 $settings->endSessionEndpoint = null;
108 } else if (is_string($config['end_session_endpoint'])) {
109 $settings->endSessionEndpoint = $config['end_session_endpoint'];
112 $settings->validate();
118 * Load the underlying OpenID Connect Provider.
120 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
122 $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
123 'httpClient' => $this->http->buildClient(5),
124 'optionProvider' => new HttpBasicAuthOptionProvider(),
127 foreach ($this->getAdditionalScopes() as $scope) {
128 $provider->addScope($scope);
135 * Get any user-defined addition/custom scopes to apply to the authentication request.
139 protected function getAdditionalScopes(): array
141 $scopeConfig = $this->config()['additional_scopes'] ?: '';
143 $scopeArr = explode(',', $scopeConfig);
144 $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
146 return array_filter($scopeArr);
150 * Calculate the display name.
152 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
154 $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
155 $displayNameAttrs = explode('|', $displayNameAttrString);
158 foreach ($displayNameAttrs as $dnAttr) {
159 $dnComponent = $token->getClaim($dnAttr) ?? '';
160 if ($dnComponent !== '') {
161 $displayName[] = $dnComponent;
165 if (count($displayName) == 0) {
166 $displayName[] = $defaultValue;
169 return implode(' ', $displayName);
173 * Extract the assigned groups from the id token.
177 protected function getUserGroups(OidcIdToken $token): array
179 $groupsAttr = $this->config()['groups_claim'];
180 if (empty($groupsAttr)) {
184 $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
185 if (!is_array($groupsList)) {
189 return array_values(array_filter($groupsList, function ($val) {
190 return is_string($val);
195 * Extract the details of a user from an ID token.
197 * @return array{name: string, email: string, external_id: string, groups: string[]}
199 protected function getUserDetails(OidcIdToken $token): array
201 $idClaim = $this->config()['external_id_claim'];
202 $id = $token->getClaim($idClaim);
205 'external_id' => $id,
206 'email' => $token->getClaim('email'),
207 'name' => $this->getUserDisplayName($token, $id),
208 'groups' => $this->getUserGroups($token),
213 * Processes a received access token for a user. Login the user when
214 * they exist, optionally registering them automatically.
216 * @throws OidcException
217 * @throws JsonDebugException
218 * @throws StoppedAuthenticationException
220 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
222 $idTokenText = $accessToken->getIdToken();
223 $idToken = new OidcIdToken(
229 session()->put("oidc_id_token", $idTokenText);
231 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
232 'access_token' => $accessToken->getToken(),
233 'expires_in' => $accessToken->getExpires(),
234 'refresh_token' => $accessToken->getRefreshToken(),
237 if (!is_null($returnClaims)) {
238 $idToken->replaceClaims($returnClaims);
241 if ($this->config()['dump_user_details']) {
242 throw new JsonDebugException($idToken->getAllClaims());
246 $idToken->validate($settings->clientId);
247 } catch (OidcInvalidTokenException $exception) {
248 throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
251 $userDetails = $this->getUserDetails($idToken);
252 $isLoggedIn = auth()->check();
254 if (empty($userDetails['email'])) {
255 throw new OidcException(trans('errors.oidc_no_email_address'));
259 throw new OidcException(trans('errors.oidc_already_logged_in'));
263 $user = $this->registrationService->findOrRegister(
264 $userDetails['name'],
265 $userDetails['email'],
266 $userDetails['external_id']
268 } catch (UserRegistrationException $exception) {
269 throw new OidcException($exception->getMessage());
272 if ($this->shouldSyncGroups()) {
273 $groups = $userDetails['groups'];
274 $detachExisting = $this->config()['remove_from_groups'];
275 $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
278 $this->loginService->login($user, 'oidc');
284 * Get the OIDC config from the application.
286 protected function config(): array
288 return config('oidc');
292 * Check if groups should be synced.
294 protected function shouldSyncGroups(): bool
296 return $this->config()['user_to_groups'] !== false;
300 * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
301 * Returns a post-app-logout redirect URL.
302 * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
303 * @throws OidcException
305 public function logout(): string
307 $oidcToken = session()->pull("oidc_id_token");
308 $defaultLogoutUrl = url($this->loginService->logout());
309 $oidcSettings = $this->getProviderSettings();
311 if (!$oidcSettings->endSessionEndpoint) {
312 return $defaultLogoutUrl;
316 'id_token_hint' => $oidcToken,
317 'post_logout_redirect_uri' => $defaultLogoutUrl,
320 $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
322 return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);