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 if ($this->config()['fetch_avatar'] && !$user->avatar()->exists() && $userDetails->picture) {
226 $this->userAvatars->assignToUserFromUrl($user, $userDetails->picture);
229 if ($this->shouldSyncGroups()) {
230 $detachExisting = $this->config()['remove_from_groups'];
231 $this->groupService->syncUserWithFoundGroups($user, $userDetails->groups ?? [], $detachExisting);
234 $this->loginService->login($user, 'oidc');
240 * @throws OidcException
242 protected function getUserDetailsFromToken(OidcIdToken $idToken, OidcAccessToken $accessToken, OidcProviderSettings $settings): OidcUserDetails
244 $userDetails = new OidcUserDetails();
245 $userDetails->populate(
247 $this->config()['external_id_claim'],
248 $this->config()['display_name_claims'] ?? '',
249 $this->config()['groups_claim'] ?? ''
252 if (!$userDetails->isFullyPopulated($this->shouldSyncGroups()) && !empty($settings->userinfoEndpoint)) {
253 $provider = $this->getProvider($settings);
254 $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
255 $response = new OidcUserinfoResponse(
256 $provider->getResponse($request),
262 $response->validate($idToken->getClaim('sub'), $settings->clientId);
263 } catch (OidcInvalidTokenException $exception) {
264 throw new OidcException("Userinfo endpoint response validation failed with error: {$exception->getMessage()}");
267 $userDetails->populate(
269 $this->config()['external_id_claim'],
270 $this->config()['display_name_claims'] ?? '',
271 $this->config()['groups_claim'] ?? ''
279 * Get the OIDC config from the application.
281 protected function config(): array
283 return config('oidc');
287 * Check if groups should be synced.
289 protected function shouldSyncGroups(): bool
291 return $this->config()['user_to_groups'] !== false;
295 * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
296 * Returns a post-app-logout redirect URL.
297 * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
298 * @throws OidcException
300 public function logout(): string
302 $oidcToken = session()->pull("oidc_id_token");
303 $defaultLogoutUrl = url($this->loginService->logout());
304 $oidcSettings = $this->getProviderSettings();
306 if (!$oidcSettings->endSessionEndpoint) {
307 return $defaultLogoutUrl;
311 'id_token_hint' => $oidcToken,
312 'post_logout_redirect_uri' => $defaultLogoutUrl,
315 $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
317 return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);