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');
65 $accessToken = new AccessToken(json_decode($json, true));
67 // Check whether the access token or ID token is expired
68 if (!$accessToken->getIdToken()->isExpired() && !$accessToken->hasExpired()) {
72 // If no refresh token available, logout
73 if ($accessToken->getRefreshToken() === null) {
74 $this->actionLogout();
78 // ID token or access token is expired, we refresh it using the refresh token
80 $provider = $this->getProvider();
82 $accessToken = $provider->getAccessToken('refresh_token', [
83 'refresh_token' => $accessToken->getRefreshToken(),
85 } catch (IdentityProviderException $e) {
86 // Refreshing failed, logout
87 $this->actionLogout();
91 // A valid token was obtained, we update the access token
92 session()->put('openid_token', json_encode($accessToken));
98 * Process the Authorization response from the authorization server and
99 * return the matching, or new if registration active, user matched to
100 * the authorization server.
101 * Returns null if not authenticated.
103 * @throws OpenIdException
104 * @throws ValidationError
105 * @throws JsonDebugException
106 * @throws UserRegistrationException
108 public function processAuthorizeResponse(?string $authorizationCode): ?User
110 $provider = $this->getProvider();
112 // Try to exchange authorization code for access token
113 $accessToken = $provider->getAccessToken('authorization_code', [
114 'code' => $authorizationCode,
117 return $this->processAccessTokenCallback($accessToken);
121 * Do the required actions to log a user out.
123 protected function actionLogout()
126 session()->invalidate();
130 * Load the underlying OpenID Connect Provider.
134 protected function getProvider(): OpenIDConnectProvider
136 $settings = $this->config['openid'];
137 $overrides = $this->config['openid_overrides'] ?? [];
139 if ($overrides && is_string($overrides)) {
140 $overrides = json_decode($overrides, true);
143 $openIdSettings = $this->loadOpenIdDetails();
144 $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
146 $signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
147 return new OpenIDConnectProvider($settings, ['signer' => $signer]);
151 * Load dynamic service provider options required by the onelogin toolkit.
153 protected function loadOpenIdDetails(): array
156 'redirectUri' => url('/openid/redirect'),
161 * Calculate the display name
163 protected function getUserDisplayName(Token $token, string $defaultValue): string
165 $displayNameAttr = $this->config['display_name_attributes'];
168 foreach ($displayNameAttr as $dnAttr) {
169 $dnComponent = $token->getClaim($dnAttr, '');
170 if ($dnComponent !== '') {
171 $displayName[] = $dnComponent;
175 if (count($displayName) == 0) {
176 $displayName = $defaultValue;
178 $displayName = implode(' ', $displayName);
185 * Get the value to use as the external id saved in BookStack
186 * used to link the user to an existing BookStack DB user.
188 protected function getExternalId(Token $token, string $defaultValue)
190 $userNameAttr = $this->config['external_id_attribute'];
191 if ($userNameAttr === null) {
192 return $defaultValue;
195 return $token->getClaim($userNameAttr, $defaultValue);
199 * Extract the details of a user from an ID token.
201 protected function getUserDetails(Token $token): array
204 $emailAttr = $this->config['email_attribute'];
205 if ($token->hasClaim($emailAttr)) {
206 $email = $token->getClaim($emailAttr);
210 'external_id' => $token->getClaim('sub'),
212 'name' => $this->getUserDisplayName($token, $email),
217 * Processes a received access token for a user. Login the user when
218 * they exist, optionally registering them automatically.
219 * @throws OpenIdException
220 * @throws JsonDebugException
221 * @throws UserRegistrationException
223 public function processAccessTokenCallback(AccessToken $accessToken): User
225 $userDetails = $this->getUserDetails($accessToken->getIdToken());
226 $isLoggedIn = auth()->check();
228 if ($this->config['dump_user_details']) {
229 throw new JsonDebugException($accessToken->jsonSerialize());
232 if ($userDetails['email'] === null) {
233 throw new OpenIdException(trans('errors.openid_no_email_address'));
237 throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
240 $user = $this->getOrRegisterUser($userDetails);
241 if ($user === null) {
242 throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
245 auth()->login($user);
246 session()->put('openid_token', json_encode($accessToken));