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 // Check if both the access token and the ID token (if present) are unexpired
75 $idToken = $accessToken->getIdToken();
76 $accessTokenUnexpired = $accessToken->getExpires() && !$accessToken->hasExpired();
77 $idTokenUnexpired = !$idToken || !$idToken->isExpired();
78 if ($accessTokenUnexpired && $idTokenUnexpired) {
82 // If no refresh token available, logout
83 if ($accessToken->getRefreshToken() === null) {
84 $this->actionLogout();
88 // ID token or access token is expired, we refresh it using the refresh token
90 $provider = $this->getProvider();
92 $accessToken = $provider->getAccessToken('refresh_token', [
93 'refresh_token' => $accessToken->getRefreshToken(),
95 } catch (IdentityProviderException $e) {
96 // Refreshing failed, logout
97 $this->actionLogout();
99 } catch (\Exception $e) {
100 // Unknown error, logout and throw
101 $this->actionLogout();
105 // A valid token was obtained, we update the access token
106 session()->put('openid_token', json_encode($accessToken));
112 * Process the Authorization response from the authorization server and
113 * return the matching, or new if registration active, user matched to
114 * the authorization server.
115 * Returns null if not authenticated.
117 * @throws OpenIdException
118 * @throws ValidationError
119 * @throws JsonDebugException
120 * @throws UserRegistrationException
122 public function processAuthorizeResponse(?string $authorizationCode): ?User
124 $provider = $this->getProvider();
126 // Try to exchange authorization code for access token
127 $accessToken = $provider->getAccessToken('authorization_code', [
128 'code' => $authorizationCode,
131 return $this->processAccessTokenCallback($accessToken);
135 * Do the required actions to log a user out.
137 protected function actionLogout()
140 session()->invalidate();
144 * Load the underlying OpenID Connect Provider.
148 protected function getProvider(): OpenIDConnectProvider
151 $settings = $this->config['openid'];
152 $overrides = $this->config['openid_overrides'] ?? [];
154 if ($overrides && is_string($overrides)) {
155 $overrides = json_decode($overrides, true);
158 $openIdSettings = $this->loadOpenIdDetails();
159 $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
162 $services = $this->loadOpenIdServices();
163 $overrides = $this->config['openid_services'] ?? [];
165 $services = array_replace_recursive($services, $overrides);
167 return new OpenIDConnectProvider($settings, $services);
171 * Load services utilized by the OpenID Connect provider.
173 protected function loadOpenIdServices(): array
176 'signer' => new \Lcobucci\JWT\Signer\Rsa\Sha256(),
181 * Load dynamic service provider options required by the OpenID Connect provider.
183 protected function loadOpenIdDetails(): array
186 'redirectUri' => url('/openid/redirect'),
191 * Calculate the display name
193 protected function getUserDisplayName(Token $token, string $defaultValue): string
195 $displayNameAttr = $this->config['display_name_attributes'];
198 foreach ($displayNameAttr as $dnAttr) {
199 $dnComponent = $token->getClaim($dnAttr, '');
200 if ($dnComponent !== '') {
201 $displayName[] = $dnComponent;
205 if (count($displayName) == 0) {
206 $displayName = $defaultValue;
208 $displayName = implode(' ', $displayName);
215 * Get the value to use as the external id saved in BookStack
216 * used to link the user to an existing BookStack DB user.
218 protected function getExternalId(Token $token, string $defaultValue)
220 $userNameAttr = $this->config['external_id_attribute'];
221 if ($userNameAttr === null) {
222 return $defaultValue;
225 return $token->getClaim($userNameAttr, $defaultValue);
229 * Extract the details of a user from an ID token.
231 protected function getUserDetails(Token $token): array
234 $emailAttr = $this->config['email_attribute'];
235 if ($token->hasClaim($emailAttr)) {
236 $email = $token->getClaim($emailAttr);
240 'external_id' => $token->getClaim('sub'),
242 'name' => $this->getUserDisplayName($token, $email),
247 * Processes a received access token for a user. Login the user when
248 * they exist, optionally registering them automatically.
249 * @throws OpenIdException
250 * @throws JsonDebugException
251 * @throws UserRegistrationException
253 public function processAccessTokenCallback(AccessToken $accessToken): User
255 $userDetails = $this->getUserDetails($accessToken->getIdToken());
256 $isLoggedIn = auth()->check();
258 if ($this->config['dump_user_details']) {
259 throw new JsonDebugException($accessToken->jsonSerialize());
262 if ($userDetails['email'] === null) {
263 throw new OpenIdException(trans('errors.openid_no_email_address'));
267 throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
270 $user = $this->getOrRegisterUser($userDetails);
271 if ($user === null) {
272 throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
275 auth()->login($user);
276 session()->put('openid_token', json_encode($accessToken));