3 namespace BookStack\Auth\Access\Oidc;
5 use BookStack\Auth\Access\GroupSyncService;
6 use Illuminate\Support\Arr;
8 use BookStack\Auth\Access\LoginService;
9 use BookStack\Auth\Access\RegistrationService;
10 use BookStack\Auth\User;
11 use BookStack\Exceptions\JsonDebugException;
12 use BookStack\Exceptions\StoppedAuthenticationException;
13 use BookStack\Exceptions\UserRegistrationException;
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;
23 * Class OpenIdConnectService
24 * Handles any app-specific OIDC tasks.
28 protected RegistrationService $registrationService;
29 protected LoginService $loginService;
30 protected HttpClient $httpClient;
31 protected GroupSyncService $groupService;
34 * OpenIdService constructor.
36 public function __construct(
37 RegistrationService $registrationService,
38 LoginService $loginService,
39 HttpClient $httpClient,
40 GroupSyncService $groupService
43 $this->registrationService = $registrationService;
44 $this->loginService = $loginService;
45 $this->httpClient = $httpClient;
46 $this->groupService = $groupService;
50 * Initiate an authorization flow.
52 * @throws OidcException
54 * @return array{url: string, state: string}
56 public function login(): array
58 $settings = $this->getProviderSettings();
59 $provider = $this->getProvider($settings);
62 'url' => $provider->getAuthorizationUrl(),
63 'state' => $provider->getState(),
68 * Process the Authorization response from the authorization server and
69 * return the matching, or new if registration active, user matched to the
70 * authorization server. Throws if the user cannot be auth if not authenticated.
72 * @throws JsonDebugException
73 * @throws OidcException
74 * @throws StoppedAuthenticationException
75 * @throws IdentityProviderException
77 public function processAuthorizeResponse(?string $authorizationCode): User
79 $settings = $this->getProviderSettings();
80 $provider = $this->getProvider($settings);
82 // Try to exchange authorization code for access token
83 $accessToken = $provider->getAccessToken('authorization_code', [
84 'code' => $authorizationCode,
87 return $this->processAccessTokenCallback($accessToken, $settings);
91 * @throws OidcException
93 protected function getProviderSettings(): OidcProviderSettings
95 $config = $this->config();
96 $settings = new OidcProviderSettings([
97 'issuer' => $config['issuer'],
98 'clientId' => $config['client_id'],
99 'clientSecret' => $config['client_secret'],
100 'redirectUri' => url('/oidc/callback'),
101 'authorizationEndpoint' => $config['authorization_endpoint'],
102 'tokenEndpoint' => $config['token_endpoint'],
105 // Use keys if configured
106 if (!empty($config['jwt_public_key'])) {
107 $settings->keys = [$config['jwt_public_key']];
111 if ($config['discover'] ?? false) {
113 $settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
114 } catch (OidcIssuerDiscoveryException $exception) {
115 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
119 $settings->validate();
125 * Load the underlying OpenID Connect Provider.
127 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
129 $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
130 'httpClient' => $this->httpClient,
131 'optionProvider' => new HttpBasicAuthOptionProvider(),
134 foreach ($this->getAdditionalScopes() as $scope) {
135 $provider->addScope($scope);
142 * Get any user-defined addition/custom scopes to apply to the authentication request.
146 protected function getAdditionalScopes(): array
148 $scopeConfig = $this->config()['additional_scopes'] ?: '';
150 $scopeArr = explode(',', $scopeConfig);
151 $scopeArr = array_map(fn(string $scope) => trim($scope), $scopeArr);
153 return array_filter($scopeArr);
157 * Calculate the display name.
159 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
161 $displayNameAttr = $this->config()['display_name_claims'];
164 foreach ($displayNameAttr as $dnAttr) {
165 $dnComponent = $token->getClaim($dnAttr) ?? '';
166 if ($dnComponent !== '') {
167 $displayName[] = $dnComponent;
171 if (count($displayName) == 0) {
172 $displayName[] = $defaultValue;
175 return implode(' ', $displayName);
179 * Extract the assigned groups from the id token.
183 protected function getUserGroups(OidcIdToken $token): array
185 $groupsAttr = $this->config()['group_attribute'];
186 if (empty($groupsAttr)) {
190 $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
191 if (!is_array($groupsList)) {
195 return array_values(array_filter($groupsList, function($val) {
196 return is_string($val);
201 * Extract the details of a user from an ID token.
203 * @return array{name: string, email: string, external_id: string, groups: string[]}
205 protected function getUserDetails(OidcIdToken $token): array
207 $id = $token->getClaim('sub');
210 'external_id' => $id,
211 'email' => $token->getClaim('email'),
212 'name' => $this->getUserDisplayName($token, $id),
213 'groups' => $this->getUserGroups($token),
218 * Processes a received access token for a user. Login the user when
219 * they exist, optionally registering them automatically.
221 * @throws OidcException
222 * @throws JsonDebugException
223 * @throws StoppedAuthenticationException
225 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
227 $idTokenText = $accessToken->getIdToken();
228 $idToken = new OidcIdToken(
234 if ($this->config()['dump_user_details']) {
235 throw new JsonDebugException($idToken->getAllClaims());
239 $idToken->validate($settings->clientId);
240 } catch (OidcInvalidTokenException $exception) {
241 throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
244 $userDetails = $this->getUserDetails($idToken);
245 $isLoggedIn = auth()->check();
247 if (empty($userDetails['email'])) {
248 throw new OidcException(trans('errors.oidc_no_email_address'));
252 throw new OidcException(trans('errors.oidc_already_logged_in'));
256 $user = $this->registrationService->findOrRegister(
257 $userDetails['name'],
258 $userDetails['email'],
259 $userDetails['external_id']
261 } catch (UserRegistrationException $exception) {
262 throw new OidcException($exception->getMessage());
265 if ($this->shouldSyncGroups()) {
266 $groups = $userDetails['groups'];
267 $detachExisting = $this->config()['remove_from_groups'];
268 $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
271 $this->loginService->login($user, 'oidc');
277 * Get the OIDC config from the application.
279 protected function config(): array
281 return config('oidc');
285 * Check if groups should be synced.
287 protected function shouldSyncGroups(): bool
289 return $this->config()['user_to_groups'] !== false;