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'],
89 // Use keys if configured
90 if (!empty($config['jwt_public_key'])) {
91 $settings->keys = [$config['jwt_public_key']];
95 if ($config['discover'] ?? false) {
97 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
98 } catch (OidcIssuerDiscoveryException $exception) {
99 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
103 $settings->validate();
109 * Load the underlying OpenID Connect Provider.
111 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
113 $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
114 'httpClient' => $this->http->buildClient(5),
115 'optionProvider' => new HttpBasicAuthOptionProvider(),
118 foreach ($this->getAdditionalScopes() as $scope) {
119 $provider->addScope($scope);
126 * Get any user-defined addition/custom scopes to apply to the authentication request.
130 protected function getAdditionalScopes(): array
132 $scopeConfig = $this->config()['additional_scopes'] ?: '';
134 $scopeArr = explode(',', $scopeConfig);
135 $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
137 return array_filter($scopeArr);
141 * Calculate the display name.
143 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
145 $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
146 $displayNameAttrs = explode('|', $displayNameAttrString);
149 foreach ($displayNameAttrs as $dnAttr) {
150 $dnComponent = $token->getClaim($dnAttr) ?? '';
151 if ($dnComponent !== '') {
152 $displayName[] = $dnComponent;
156 if (count($displayName) == 0) {
157 $displayName[] = $defaultValue;
160 return implode(' ', $displayName);
164 * Extract the assigned groups from the id token.
168 protected function getUserGroups(OidcIdToken $token): array
170 $groupsAttr = $this->config()['groups_claim'];
171 if (empty($groupsAttr)) {
175 $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
176 if (!is_array($groupsList)) {
180 return array_values(array_filter($groupsList, function ($val) {
181 return is_string($val);
186 * Extract the details of a user from an ID token.
188 * @return array{name: string, email: string, external_id: string, groups: string[]}
190 protected function getUserDetails(OidcIdToken $token): array
192 $idClaim = $this->config()['external_id_claim'];
193 $id = $token->getClaim($idClaim);
196 'external_id' => $id,
197 'email' => $token->getClaim('email'),
198 'name' => $this->getUserDisplayName($token, $id),
199 'groups' => $this->getUserGroups($token),
204 * Processes a received access token for a user. Login the user when
205 * they exist, optionally registering them automatically.
207 * @throws OidcException
208 * @throws JsonDebugException
209 * @throws StoppedAuthenticationException
211 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
213 $idTokenText = $accessToken->getIdToken();
214 $idToken = new OidcIdToken(
220 // OIDC Logout Feature: Temporarily save token in session
221 $access_token_for_logout = $idTokenText;
222 session()->put("oidctoken", $access_token_for_logout);
226 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
227 'access_token' => $accessToken->getToken(),
228 'expires_in' => $accessToken->getExpires(),
229 'refresh_token' => $accessToken->getRefreshToken(),
232 if (!is_null($returnClaims)) {
233 $idToken->replaceClaims($returnClaims);
236 if ($this->config()['dump_user_details']) {
237 throw new JsonDebugException($idToken->getAllClaims());
241 $idToken->validate($settings->clientId);
242 } catch (OidcInvalidTokenException $exception) {
243 throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
246 $userDetails = $this->getUserDetails($idToken);
247 $isLoggedIn = auth()->check();
249 if (empty($userDetails['email'])) {
250 throw new OidcException(trans('errors.oidc_no_email_address'));
254 throw new OidcException(trans('errors.oidc_already_logged_in'));
258 $user = $this->registrationService->findOrRegister(
259 $userDetails['name'],
260 $userDetails['email'],
261 $userDetails['external_id']
263 } catch (UserRegistrationException $exception) {
264 throw new OidcException($exception->getMessage());
267 if ($this->shouldSyncGroups()) {
268 $groups = $userDetails['groups'];
269 $detachExisting = $this->config()['remove_from_groups'];
270 $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
273 $this->loginService->login($user, 'oidc');
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;
296 * OIDC Logout Feature: Initiate a logout flow.
298 * @throws OidcException
302 public function logout() {
304 $config = $this->config();
305 $app_url = env('APP_URL', '');
306 $end_session_endpoint = $config["end_session_endpoint"];
308 $oidctoken = session()->get("oidctoken");
309 session()->invalidate();
311 if (str_contains($app_url, 'https://')) {
312 $protocol = 'https://';
314 $protocol = 'http://';
319 return redirect($end_session_endpoint.'?id_token_hint='.$oidctoken."&post_logout_redirect_uri=".$protocol.$_SERVER['HTTP_HOST']."/");