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' => $config['end_session_endpoint'],
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 if ($config['end_session_endpoint'] === false) {
106 $settings->endSessionEndpoint = null;
109 $settings->validate();
115 * Load the underlying OpenID Connect Provider.
117 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
119 $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
120 'httpClient' => $this->http->buildClient(5),
121 'optionProvider' => new HttpBasicAuthOptionProvider(),
124 foreach ($this->getAdditionalScopes() as $scope) {
125 $provider->addScope($scope);
132 * Get any user-defined addition/custom scopes to apply to the authentication request.
136 protected function getAdditionalScopes(): array
138 $scopeConfig = $this->config()['additional_scopes'] ?: '';
140 $scopeArr = explode(',', $scopeConfig);
141 $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
143 return array_filter($scopeArr);
147 * Calculate the display name.
149 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
151 $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
152 $displayNameAttrs = explode('|', $displayNameAttrString);
155 foreach ($displayNameAttrs as $dnAttr) {
156 $dnComponent = $token->getClaim($dnAttr) ?? '';
157 if ($dnComponent !== '') {
158 $displayName[] = $dnComponent;
162 if (count($displayName) == 0) {
163 $displayName[] = $defaultValue;
166 return implode(' ', $displayName);
170 * Extract the assigned groups from the id token.
174 protected function getUserGroups(OidcIdToken $token): array
176 $groupsAttr = $this->config()['groups_claim'];
177 if (empty($groupsAttr)) {
181 $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
182 if (!is_array($groupsList)) {
186 return array_values(array_filter($groupsList, function ($val) {
187 return is_string($val);
192 * Extract the details of a user from an ID token.
194 * @return array{name: string, email: string, external_id: string, groups: string[]}
196 protected function getUserDetails(OidcIdToken $token): array
198 $idClaim = $this->config()['external_id_claim'];
199 $id = $token->getClaim($idClaim);
202 'external_id' => $id,
203 'email' => $token->getClaim('email'),
204 'name' => $this->getUserDisplayName($token, $id),
205 'groups' => $this->getUserGroups($token),
210 * Processes a received access token for a user. Login the user when
211 * they exist, optionally registering them automatically.
213 * @throws OidcException
214 * @throws JsonDebugException
215 * @throws StoppedAuthenticationException
217 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
219 $idTokenText = $accessToken->getIdToken();
220 $idToken = new OidcIdToken(
226 session()->put("oidc_id_token", $idTokenText);
228 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
229 'access_token' => $accessToken->getToken(),
230 'expires_in' => $accessToken->getExpires(),
231 'refresh_token' => $accessToken->getRefreshToken(),
234 if (!is_null($returnClaims)) {
235 $idToken->replaceClaims($returnClaims);
238 if ($this->config()['dump_user_details']) {
239 throw new JsonDebugException($idToken->getAllClaims());
243 $idToken->validate($settings->clientId);
244 } catch (OidcInvalidTokenException $exception) {
245 throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
248 $userDetails = $this->getUserDetails($idToken);
249 $isLoggedIn = auth()->check();
251 if (empty($userDetails['email'])) {
252 throw new OidcException(trans('errors.oidc_no_email_address'));
256 throw new OidcException(trans('errors.oidc_already_logged_in'));
260 $user = $this->registrationService->findOrRegister(
261 $userDetails['name'],
262 $userDetails['email'],
263 $userDetails['external_id']
265 } catch (UserRegistrationException $exception) {
266 throw new OidcException($exception->getMessage());
269 if ($this->shouldSyncGroups()) {
270 $groups = $userDetails['groups'];
271 $detachExisting = $this->config()['remove_from_groups'];
272 $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
275 $this->loginService->login($user, 'oidc');
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 return $oidcSettings->endSessionEndpoint . '?' . http_build_query($endpointParams);