1 <?php namespace BookStack\Auth\Access\Oidc;
3 use BookStack\Auth\Access\LoginService;
4 use BookStack\Auth\Access\RegistrationService;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\JsonDebugException;
7 use BookStack\Exceptions\OpenIdConnectException;
8 use BookStack\Exceptions\StoppedAuthenticationException;
9 use BookStack\Exceptions\UserRegistrationException;
11 use GuzzleHttp\Client;
12 use Illuminate\Support\Facades\Cache;
13 use Psr\Http\Client\ClientExceptionInterface;
20 * Class OpenIdConnectService
21 * Handles any app-specific OIDC tasks.
25 protected $registrationService;
26 protected $loginService;
30 * OpenIdService constructor.
32 public function __construct(RegistrationService $registrationService, LoginService $loginService)
34 $this->config = config('oidc');
35 $this->registrationService = $registrationService;
36 $this->loginService = $loginService;
40 * Initiate an authorization flow.
41 * @return array{url: string, state: string}
43 public function login(): array
45 $settings = $this->getProviderSettings();
46 $provider = $this->getProvider($settings);
48 'url' => $provider->getAuthorizationUrl(),
49 'state' => $provider->getState(),
54 * Process the Authorization response from the authorization server and
55 * return the matching, or new if registration active, user matched to
56 * the authorization server.
57 * Returns null if not authenticated.
59 * @throws ClientExceptionInterface
61 public function processAuthorizeResponse(?string $authorizationCode): ?User
63 $settings = $this->getProviderSettings();
64 $provider = $this->getProvider($settings);
66 // Try to exchange authorization code for access token
67 $accessToken = $provider->getAccessToken('authorization_code', [
68 'code' => $authorizationCode,
71 return $this->processAccessTokenCallback($accessToken, $settings);
75 * @throws OidcIssuerDiscoveryException
76 * @throws ClientExceptionInterface
78 protected function getProviderSettings(): OidcProviderSettings
80 $settings = new OidcProviderSettings([
81 'issuer' => $this->config['issuer'],
82 'clientId' => $this->config['client_id'],
83 'clientSecret' => $this->config['client_secret'],
84 'redirectUri' => url('/oidc/redirect'),
85 'authorizationEndpoint' => $this->config['authorization_endpoint'],
86 'tokenEndpoint' => $this->config['token_endpoint'],
89 // Use keys if configured
90 if (!empty($this->config['jwt_public_key'])) {
91 $settings->keys = [$this->config['jwt_public_key']];
95 if ($this->config['discover'] ?? false) {
96 $settings->discoverFromIssuer(new Client(['timeout' => 3]), Cache::store(null), 15);
99 $settings->validate();
105 * Load the underlying OpenID Connect Provider.
107 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
109 return new OidcOAuthProvider($settings->arrayForProvider());
113 * Calculate the display name
115 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
117 $displayNameAttr = $this->config['display_name_claims'];
120 foreach ($displayNameAttr as $dnAttr) {
121 $dnComponent = $token->getClaim($dnAttr) ?? '';
122 if ($dnComponent !== '') {
123 $displayName[] = $dnComponent;
127 if (count($displayName) == 0) {
128 $displayName[] = $defaultValue;
131 return implode(' ', $displayName);
135 * Extract the details of a user from an ID token.
136 * @return array{name: string, email: string, external_id: string}
138 protected function getUserDetails(OidcIdToken $token): array
140 $id = $token->getClaim('sub');
142 'external_id' => $id,
143 'email' => $token->getClaim('email'),
144 'name' => $this->getUserDisplayName($token, $id),
149 * Processes a received access token for a user. Login the user when
150 * they exist, optionally registering them automatically.
151 * @throws OpenIdConnectException
152 * @throws JsonDebugException
153 * @throws UserRegistrationException
154 * @throws StoppedAuthenticationException
156 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
158 $idTokenText = $accessToken->getIdToken();
159 $idToken = new OidcIdToken(
165 if ($this->config['dump_user_details']) {
166 throw new JsonDebugException($idToken->getAllClaims());
170 $idToken->validate($settings->clientId);
171 } catch (OidcInvalidTokenException $exception) {
172 throw new OpenIdConnectException("ID token validate failed with error: {$exception->getMessage()}");
175 $userDetails = $this->getUserDetails($idToken);
176 $isLoggedIn = auth()->check();
178 if ($userDetails['email'] === null) {
179 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
183 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
186 $user = $this->registrationService->findOrRegister(
187 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
190 if ($user === null) {
191 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
194 $this->loginService->login($user, 'oidc');