3 namespace BookStack\Auth\Access\Oidc;
5 use BookStack\Auth\Access\GroupSyncService;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\RegistrationService;
8 use BookStack\Auth\User;
9 use BookStack\Exceptions\JsonDebugException;
10 use BookStack\Exceptions\StoppedAuthenticationException;
11 use BookStack\Exceptions\UserRegistrationException;
12 use BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
14 use Illuminate\Support\Arr;
15 use Illuminate\Support\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
18 use Psr\Http\Client\ClientInterface as HttpClient;
21 * Class OpenIdConnectService
22 * Handles any app-specific OIDC tasks.
26 public function __construct(
27 protected RegistrationService $registrationService,
28 protected LoginService $loginService,
29 protected HttpClient $httpClient,
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->httpClient, 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->httpClient,
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 $displayNameAttr = $this->config()['display_name_claims'];
148 foreach ($displayNameAttr as $dnAttr) {
149 $dnComponent = $token->getClaim($dnAttr) ?? '';
150 if ($dnComponent !== '') {
151 $displayName[] = $dnComponent;
155 if (count($displayName) == 0) {
156 $displayName[] = $defaultValue;
159 return implode(' ', $displayName);
163 * Extract the assigned groups from the id token.
167 protected function getUserGroups(OidcIdToken $token): array
169 $groupsAttr = $this->config()['groups_claim'];
170 if (empty($groupsAttr)) {
174 $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
175 if (!is_array($groupsList)) {
179 return array_values(array_filter($groupsList, function ($val) {
180 return is_string($val);
185 * Extract the details of a user from an ID token.
187 * @return array{name: string, email: string, external_id: string, groups: string[]}
189 protected function getUserDetails(OidcIdToken $token): array
191 $idClaim = $this->config()['external_id_claim'];
192 $id = $token->getClaim($idClaim);
195 'external_id' => $id,
196 'email' => $token->getClaim('email'),
197 'name' => $this->getUserDisplayName($token, $id),
198 'groups' => $this->getUserGroups($token),
203 * Processes a received access token for a user. Login the user when
204 * they exist, optionally registering them automatically.
206 * @throws OidcException
207 * @throws JsonDebugException
208 * @throws StoppedAuthenticationException
210 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
212 $idTokenText = $accessToken->getIdToken();
213 $idToken = new OidcIdToken(
219 $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
220 'access_token' => $accessToken->getToken(),
221 'expires_in' => $accessToken->getExpires(),
222 'refresh_token' => $accessToken->getRefreshToken(),
225 if (!is_null($returnClaims)) {
226 $idToken->replaceClaims($returnClaims);
229 if ($this->config()['dump_user_details']) {
230 throw new JsonDebugException($idToken->getAllClaims());
234 $idToken->validate($settings->clientId);
235 } catch (OidcInvalidTokenException $exception) {
236 throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
239 $userDetails = $this->getUserDetails($idToken);
240 $isLoggedIn = auth()->check();
242 if (empty($userDetails['email'])) {
243 throw new OidcException(trans('errors.oidc_no_email_address'));
247 throw new OidcException(trans('errors.oidc_already_logged_in'));
251 $user = $this->registrationService->findOrRegister(
252 $userDetails['name'],
253 $userDetails['email'],
254 $userDetails['external_id']
256 } catch (UserRegistrationException $exception) {
257 throw new OidcException($exception->getMessage());
260 if ($this->shouldSyncGroups()) {
261 $groups = $userDetails['groups'];
262 $detachExisting = $this->config()['remove_from_groups'];
263 $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
266 $this->loginService->login($user, 'oidc');
272 * Get the OIDC config from the application.
274 protected function config(): array
276 return config('oidc');
280 * Check if groups should be synced.
282 protected function shouldSyncGroups(): bool
284 return $this->config()['user_to_groups'] !== false;