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 OpenIDConnectClient\AccessToken;
10 use OpenIDConnectClient\OpenIDConnectProvider;
14 * Handles any app-specific OpenId tasks.
16 class OpenIdService extends ExternalAuthService
21 * OpenIdService constructor.
23 public function __construct(RegistrationService $registrationService, User $user)
25 parent::__construct($registrationService, $user);
27 $this->config = config('openid');
31 * Initiate a authorization flow.
34 public function login(): array
36 $provider = $this->getProvider();
38 'url' => $provider->getAuthorizationUrl(),
39 'state' => $provider->getState(),
44 * Initiate a logout flow.
47 public function logout(): array
49 $this->actionLogout();
53 return ['url' => $url, 'id' => $id];
57 * Process the Authorization response from the authorization server and
58 * return the matching, or new if registration active, user matched to
59 * the authorization server.
60 * Returns null if not authenticated.
62 * @throws OpenIdException
63 * @throws ValidationError
64 * @throws JsonDebugException
65 * @throws UserRegistrationException
67 public function processAuthorizeResponse(?string $authorizationCode): ?User
69 $provider = $this->getProvider();
71 // Try to exchange authorization code for access token
72 $accessToken = $provider->getAccessToken('authorization_code', [
73 'code' => $authorizationCode,
76 return $this->processAccessTokenCallback($accessToken);
80 * Do the required actions to log a user out.
82 protected function actionLogout()
85 session()->invalidate();
89 * Load the underlying Onelogin SAML2 toolkit.
93 protected function getProvider(): OpenIDConnectProvider
95 $settings = $this->config['openid'];
96 $overrides = $this->config['openid_overrides'] ?? [];
98 if ($overrides && is_string($overrides)) {
99 $overrides = json_decode($overrides, true);
102 $openIdSettings = $this->loadOpenIdDetails();
103 $settings = array_replace_recursive($settings, $openIdSettings, $overrides);
105 $signer = new \Lcobucci\JWT\Signer\Rsa\Sha256();
106 return new OpenIDConnectProvider($settings, ['signer' => $signer]);
110 * Load dynamic service provider options required by the onelogin toolkit.
112 protected function loadOpenIdDetails(): array
115 'redirectUri' => url('/openid/redirect'),
120 * Calculate the display name
122 protected function getUserDisplayName(Token $token, string $defaultValue): string
124 $displayNameAttr = $this->config['display_name_attributes'];
127 foreach ($displayNameAttr as $dnAttr) {
128 $dnComponent = $token->getClaim($dnAttr, '');
129 if ($dnComponent !== '') {
130 $displayName[] = $dnComponent;
134 if (count($displayName) == 0) {
135 $displayName = $defaultValue;
137 $displayName = implode(' ', $displayName);
144 * Get the value to use as the external id saved in BookStack
145 * used to link the user to an existing BookStack DB user.
147 protected function getExternalId(Token $token, string $defaultValue)
149 $userNameAttr = $this->config['external_id_attribute'];
150 if ($userNameAttr === null) {
151 return $defaultValue;
154 return $token->getClaim($userNameAttr, $defaultValue);
158 * Extract the details of a user from a SAML response.
160 protected function getUserDetails(Token $token): array
163 $emailAttr = $this->config['email_attribute'];
164 if ($token->hasClaim($emailAttr)) {
165 $email = $token->getClaim($emailAttr);
169 'external_id' => $token->getClaim('sub'),
171 'name' => $this->getUserDisplayName($token, $email),
176 * Processes a received access token for a user. Login the user when
177 * they exist, optionally registering them automatically.
178 * @throws OpenIdException
179 * @throws JsonDebugException
180 * @throws UserRegistrationException
182 public function processAccessTokenCallback(AccessToken $accessToken): User
184 $userDetails = $this->getUserDetails($accessToken->getIdToken());
185 $isLoggedIn = auth()->check();
187 if ($this->config['dump_user_details']) {
188 throw new JsonDebugException($accessToken->jsonSerialize());
191 if ($userDetails['email'] === null) {
192 throw new OpenIdException(trans('errors.openid_no_email_address'));
196 throw new OpenIdException(trans('errors.openid_already_logged_in'), '/login');
199 $user = $this->getOrRegisterUser($userDetails);
200 if ($user === null) {
201 throw new OpenIdException(trans('errors.openid_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
204 auth()->login($user);