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 Illuminate\Support\Facades\Cache;
12 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
13 use Psr\Http\Client\ClientExceptionInterface;
14 use Psr\Http\Client\ClientInterface as HttpClient;
21 * Class OpenIdConnectService
22 * Handles any app-specific OIDC tasks.
26 protected $registrationService;
27 protected $loginService;
28 protected $httpClient;
31 * OpenIdService constructor.
33 public function __construct(RegistrationService $registrationService, LoginService $loginService, HttpClient $httpClient)
35 $this->registrationService = $registrationService;
36 $this->loginService = $loginService;
37 $this->httpClient = $httpClient;
41 * Initiate an authorization flow.
42 * @return array{url: string, state: string}
44 public function login(): array
46 $settings = $this->getProviderSettings();
47 $provider = $this->getProvider($settings);
49 'url' => $provider->getAuthorizationUrl(),
50 'state' => $provider->getState(),
55 * Process the Authorization response from the authorization server and
56 * return the matching, or new if registration active, user matched to
57 * the authorization server.
58 * Returns null if not authenticated.
60 * @throws ClientExceptionInterface
62 public function processAuthorizeResponse(?string $authorizationCode): ?User
64 $settings = $this->getProviderSettings();
65 $provider = $this->getProvider($settings);
67 // Try to exchange authorization code for access token
68 $accessToken = $provider->getAccessToken('authorization_code', [
69 'code' => $authorizationCode,
72 return $this->processAccessTokenCallback($accessToken, $settings);
76 * @throws OidcIssuerDiscoveryException
77 * @throws ClientExceptionInterface
79 protected function getProviderSettings(): OidcProviderSettings
81 $config = $this->config();
82 $settings = new OidcProviderSettings([
83 'issuer' => $config['issuer'],
84 'clientId' => $config['client_id'],
85 'clientSecret' => $config['client_secret'],
86 'redirectUri' => url('/oidc/callback'),
87 'authorizationEndpoint' => $config['authorization_endpoint'],
88 'tokenEndpoint' => $config['token_endpoint'],
91 // Use keys if configured
92 if (!empty($config['jwt_public_key'])) {
93 $settings->keys = [$config['jwt_public_key']];
97 if ($config['discover'] ?? false) {
98 $settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
101 $settings->validate();
107 * Load the underlying OpenID Connect Provider.
109 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
111 return new OidcOAuthProvider($settings->arrayForProvider(), [
112 'httpClient' => $this->httpClient,
113 'optionProvider' => new HttpBasicAuthOptionProvider(),
118 * Calculate the display name
120 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
122 $displayNameAttr = $this->config()['display_name_claims'];
125 foreach ($displayNameAttr as $dnAttr) {
126 $dnComponent = $token->getClaim($dnAttr) ?? '';
127 if ($dnComponent !== '') {
128 $displayName[] = $dnComponent;
132 if (count($displayName) == 0) {
133 $displayName[] = $defaultValue;
136 return implode(' ', $displayName);
140 * Extract the details of a user from an ID token.
141 * @return array{name: string, email: string, external_id: string}
143 protected function getUserDetails(OidcIdToken $token): array
145 $id = $token->getClaim('sub');
147 'external_id' => $id,
148 'email' => $token->getClaim('email'),
149 'name' => $this->getUserDisplayName($token, $id),
154 * Processes a received access token for a user. Login the user when
155 * they exist, optionally registering them automatically.
156 * @throws OpenIdConnectException
157 * @throws JsonDebugException
158 * @throws UserRegistrationException
159 * @throws StoppedAuthenticationException
161 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
163 $idTokenText = $accessToken->getIdToken();
164 $idToken = new OidcIdToken(
170 if ($this->config()['dump_user_details']) {
171 throw new JsonDebugException($idToken->getAllClaims());
175 $idToken->validate($settings->clientId);
176 } catch (OidcInvalidTokenException $exception) {
177 throw new OpenIdConnectException("ID token validate failed with error: {$exception->getMessage()}");
180 $userDetails = $this->getUserDetails($idToken);
181 $isLoggedIn = auth()->check();
183 if (empty($userDetails['email'])) {
184 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
188 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
191 $user = $this->registrationService->findOrRegister(
192 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
195 if ($user === null) {
196 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
199 $this->loginService->login($user, 'oidc');
204 * Get the OIDC config from the application.
206 protected function config(): array
208 return config('oidc');