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();
98 protected function isUnexpired(AccessToken $accessToken): bool
100 $idToken = $accessToken->getIdToken();
102 $accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
103 $idTokenUnexpired = !$idToken || !$idToken->isExpired();
105 return $accessTokenUnexpired && $idTokenUnexpired;
108 protected function refreshAccessToken(AccessToken $accessToken): ?AccessToken
110 // If no refresh token available, abort
111 if ($accessToken->getRefreshToken() === null) {
115 // ID token or access token is expired, we refresh it using the refresh token
117 return $this->getProvider()->getAccessToken('refresh_token', [
118 'refresh_token' => $accessToken->getRefreshToken(),
120 } catch (IdentityProviderException $e) {
127 * Process the Authorization response from the authorization server and
128 * return the matching, or new if registration active, user matched to
129 * the authorization server.
130 * Returns null if not authenticated.
132 * @throws OpenIdException
133 * @throws ValidationError
134 * @throws JsonDebugException
135 * @throws UserRegistrationException
137 public function processAuthorizeResponse(?string $authorizationCode): ?User
139 $provider = $this->getProvider();
141 // Try to exchange authorization code for access token
142 $accessToken = $provider->getAccessToken('authorization_code', [
143 'code' => $authorizationCode,
146 return $this->processAccessTokenCallback($accessToken);
150 * Do the required actions to log a user out.
152 protected function actionLogout()
155 session()->invalidate();
159 * Load the underlying OpenID Connect Provider.
163 protected function getProvider(): OpenIDConnectProvider
166 $settings = $this->config['openid'];
167 $overrides = $this->config['openid_overrides'] ?? [];
169 if ($overrides && is_string($overrides)) {
170 $overrides = json_decode($overrides, true);
173 $openIdSettings = $this->loadOpenIdDetails();
174 $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
177 $services = $this->loadOpenIdServices();
178 $overrides = $this->config['openid_services'] ?? [];
180 $services = array_replace_recursive($services, $overrides);
182 return new OpenIDConnectProvider($settings, $services);
186 * Load services utilized by the OpenID Connect provider.
188 protected function loadOpenIdServices(): array
191 'signer' => new \Lcobucci\JWT\Signer\Rsa\Sha256(),
196 * Load dynamic service provider options required by the OpenID Connect provider.
198 protected function loadOpenIdDetails(): array
201 'redirectUri' => url('/openid/redirect'),
206 * Calculate the display name
208 protected function getUserDisplayName(Token $token, string $defaultValue): string
210 $displayNameAttr = $this->config['display_name_attributes'];
213 foreach ($displayNameAttr as $dnAttr) {
214 $dnComponent = $token->getClaim($dnAttr, '');
215 if ($dnComponent !== '') {
216 $displayName[] = $dnComponent;
220 if (count($displayName) == 0) {
221 $displayName = $defaultValue;
223 $displayName = implode(' ', $displayName);
230 * Get the value to use as the external id saved in BookStack
231 * used to link the user to an existing BookStack DB user.
233 protected function getExternalId(Token $token, string $defaultValue)
235 $userNameAttr = $this->config['external_id_attribute'];
236 if ($userNameAttr === null) {
237 return $defaultValue;
240 return $token->getClaim($userNameAttr, $defaultValue);
244 * Extract the details of a user from an ID token.
246 protected function getUserDetails(Token $token): array
249 $emailAttr = $this->config['email_attribute'];
250 if ($token->hasClaim($emailAttr)) {
251 $email = $token->getClaim($emailAttr);
255 'external_id' => $token->getClaim('sub'),
257 'name' => $this->getUserDisplayName($token, $email),
262 * Processes a received access token for a user. Login the user when
263 * they exist, optionally registering them automatically.
264 * @throws OpenIdException
265 * @throws JsonDebugException
266 * @throws UserRegistrationException
268 public function processAccessTokenCallback(AccessToken $accessToken): User
270 $userDetails = $this->getUserDetails($accessToken->getIdToken());
271 $isLoggedIn = auth()->check();
273 if ($this->config['dump_user_details']) {
274 throw new JsonDebugException($accessToken->jsonSerialize());
277 if ($userDetails['email'] === null) {
278 throw new OpenIdException(trans('errors.openid_no_email_address'));
282 throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
285 $user = $this->getOrRegisterUser($userDetails);
286 if ($user === null) {
287 throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
290 auth()->login($user);
291 session()->put('openid_token', json_encode($accessToken));