1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\OpenIdException;
6 use BookStack\Exceptions\UserRegistrationException;
8 use Lcobucci\JWT\Token;
9 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
10 use OpenIDConnectClient\AccessToken;
11 use OpenIDConnectClient\OpenIDConnectProvider;
15 * Handles any app-specific OpenId tasks.
17 class OpenIdService extends ExternalAuthService
22 * OpenIdService constructor.
24 public function __construct(RegistrationService $registrationService, User $user)
26 parent::__construct($registrationService, $user);
28 $this->config = config('openid');
32 * Initiate a authorization flow.
35 public function login(): array
37 $provider = $this->getProvider();
39 'url' => $provider->getAuthorizationUrl(),
40 'state' => $provider->getState(),
45 * Initiate a logout flow.
48 public function logout(): array
50 $this->actionLogout();
54 return ['url' => $url, 'id' => $id];
58 * Refresh the currently logged in user.
61 public function refresh(): bool
63 // Retrieve access token for current session
64 $json = session()->get('openid_token');
66 // If no access token was found, reject the refresh
68 $this->actionLogout();
72 $accessToken = new AccessToken(json_decode($json, true) ?? []);
74 // If the token is not expired, refreshing isn't necessary
75 if ($this->isUnexpired($accessToken)) {
79 // Try to obtain refreshed access token
81 $newAccessToken = $this->refreshAccessToken($accessToken);
82 } catch (\Exception $e) {
83 // Log out if an unknown problem arises
84 $this->actionLogout();
88 // If a token was obtained, update the access token, otherwise log out
89 if ($newAccessToken !== null) {
90 session()->put('openid_token', json_encode($newAccessToken));
93 $this->actionLogout();
99 * Check whether an access token or OpenID token isn't expired.
101 protected function isUnexpired(AccessToken $accessToken): bool
103 $idToken = $accessToken->getIdToken();
105 $accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
106 $idTokenUnexpired = !$idToken || !$idToken->isExpired();
108 return $accessTokenUnexpired && $idTokenUnexpired;
112 * Generate an updated access token, through the associated refresh token.
115 protected function refreshAccessToken(AccessToken $accessToken): ?AccessToken
117 // If no refresh token available, abort
118 if ($accessToken->getRefreshToken() === null) {
122 // ID token or access token is expired, we refresh it using the refresh token
124 return $this->getProvider()->getAccessToken('refresh_token', [
125 'refresh_token' => $accessToken->getRefreshToken(),
127 } catch (IdentityProviderException $e) {
134 * Process the Authorization response from the authorization server and
135 * return the matching, or new if registration active, user matched to
136 * the authorization server.
137 * Returns null if not authenticated.
139 * @throws OpenIdException
140 * @throws ValidationError
141 * @throws JsonDebugException
142 * @throws UserRegistrationException
144 public function processAuthorizeResponse(?string $authorizationCode): ?User
146 $provider = $this->getProvider();
148 // Try to exchange authorization code for access token
149 $accessToken = $provider->getAccessToken('authorization_code', [
150 'code' => $authorizationCode,
153 return $this->processAccessTokenCallback($accessToken);
157 * Do the required actions to log a user out.
159 protected function actionLogout()
162 session()->invalidate();
166 * Load the underlying OpenID Connect Provider.
170 protected function getProvider(): OpenIDConnectProvider
173 $settings = $this->config['openid'];
174 $overrides = $this->config['openid_overrides'] ?? [];
176 if ($overrides && is_string($overrides)) {
177 $overrides = json_decode($overrides, true);
180 $openIdSettings = $this->loadOpenIdDetails();
181 $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
184 $services = $this->loadOpenIdServices();
185 $overrides = $this->config['openid_services'] ?? [];
187 $services = array_replace_recursive($services, $overrides);
189 return new OpenIDConnectProvider($settings, $services);
193 * Load services utilized by the OpenID Connect provider.
195 protected function loadOpenIdServices(): array
198 'signer' => new \Lcobucci\JWT\Signer\Rsa\Sha256(),
203 * Load dynamic service provider options required by the OpenID Connect provider.
205 protected function loadOpenIdDetails(): array
208 'redirectUri' => url('/openid/redirect'),
213 * Calculate the display name
215 protected function getUserDisplayName(Token $token, string $defaultValue): string
217 $displayNameAttr = $this->config['display_name_attributes'];
220 foreach ($displayNameAttr as $dnAttr) {
221 $dnComponent = $token->getClaim($dnAttr, '');
222 if ($dnComponent !== '') {
223 $displayName[] = $dnComponent;
227 if (count($displayName) == 0) {
228 $displayName = $defaultValue;
230 $displayName = implode(' ', $displayName);
237 * Get the value to use as the external id saved in BookStack
238 * used to link the user to an existing BookStack DB user.
240 protected function getExternalId(Token $token, string $defaultValue)
242 $userNameAttr = $this->config['external_id_attribute'];
243 if ($userNameAttr === null) {
244 return $defaultValue;
247 return $token->getClaim($userNameAttr, $defaultValue);
251 * Extract the details of a user from an ID token.
253 protected function getUserDetails(Token $token): array
256 $emailAttr = $this->config['email_attribute'];
257 if ($token->hasClaim($emailAttr)) {
258 $email = $token->getClaim($emailAttr);
262 'external_id' => $token->getClaim('sub'),
264 'name' => $this->getUserDisplayName($token, $email),
269 * Processes a received access token for a user. Login the user when
270 * they exist, optionally registering them automatically.
271 * @throws OpenIdException
272 * @throws JsonDebugException
273 * @throws UserRegistrationException
275 public function processAccessTokenCallback(AccessToken $accessToken): User
277 $userDetails = $this->getUserDetails($accessToken->getIdToken());
278 $isLoggedIn = auth()->check();
280 if ($this->config['dump_user_details']) {
281 throw new JsonDebugException($accessToken->jsonSerialize());
284 if ($userDetails['email'] === null) {
285 throw new OpenIdException(trans('errors.openid_no_email_address'));
289 throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
292 $user = $this->getOrRegisterUser($userDetails);
293 if ($user === null) {
294 throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
297 auth()->login($user);
298 session()->put('openid_token', json_encode($accessToken));