3 namespace BookStack\Auth\Access\Oidc;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\RegistrationService;
8 use BookStack\Auth\User;
9 use BookStack\Exceptions\JsonDebugException;
10 use BookStack\Exceptions\OpenIdConnectException;
11 use BookStack\Exceptions\StoppedAuthenticationException;
12 use BookStack\Exceptions\UserRegistrationException;
15 use Illuminate\Support\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use Psr\Http\Client\ClientExceptionInterface;
18 use Psr\Http\Client\ClientInterface as HttpClient;
23 * Class OpenIdConnectService
24 * Handles any app-specific OIDC tasks.
28 protected $registrationService;
29 protected $loginService;
30 protected $httpClient;
33 * OpenIdService constructor.
35 public function __construct(RegistrationService $registrationService, LoginService $loginService, HttpClient $httpClient)
37 $this->registrationService = $registrationService;
38 $this->loginService = $loginService;
39 $this->httpClient = $httpClient;
43 * Initiate an authorization flow.
45 * @return array{url: string, state: string}
47 public function login(): array
49 $settings = $this->getProviderSettings();
50 $provider = $this->getProvider($settings);
53 'url' => $provider->getAuthorizationUrl(),
54 'state' => $provider->getState(),
59 * Process the Authorization response from the authorization server and
60 * return the matching, or new if registration active, user matched to
61 * the authorization server.
62 * Returns null if not authenticated.
65 * @throws ClientExceptionInterface
67 public function processAuthorizeResponse(?string $authorizationCode): ?User
69 $settings = $this->getProviderSettings();
70 $provider = $this->getProvider($settings);
72 // Try to exchange authorization code for access token
73 $accessToken = $provider->getAccessToken('authorization_code', [
74 'code' => $authorizationCode,
77 return $this->processAccessTokenCallback($accessToken, $settings);
81 * @throws OidcIssuerDiscoveryException
82 * @throws ClientExceptionInterface
84 protected function getProviderSettings(): OidcProviderSettings
86 $config = $this->config();
87 $settings = new OidcProviderSettings([
88 'issuer' => $config['issuer'],
89 'clientId' => $config['client_id'],
90 'clientSecret' => $config['client_secret'],
91 'redirectUri' => url('/oidc/callback'),
92 'authorizationEndpoint' => $config['authorization_endpoint'],
93 'tokenEndpoint' => $config['token_endpoint'],
96 // Use keys if configured
97 if (!empty($config['jwt_public_key'])) {
98 $settings->keys = [$config['jwt_public_key']];
102 if ($config['discover'] ?? false) {
103 $settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
106 $settings->validate();
112 * Load the underlying OpenID Connect Provider.
114 protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
116 return new OidcOAuthProvider($settings->arrayForProvider(), [
117 'httpClient' => $this->httpClient,
118 'optionProvider' => new HttpBasicAuthOptionProvider(),
123 * Calculate the display name.
125 protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
127 $displayNameAttr = $this->config()['display_name_claims'];
130 foreach ($displayNameAttr as $dnAttr) {
131 $dnComponent = $token->getClaim($dnAttr) ?? '';
132 if ($dnComponent !== '') {
133 $displayName[] = $dnComponent;
137 if (count($displayName) == 0) {
138 $displayName[] = $defaultValue;
141 return implode(' ', $displayName);
145 * Extract the details of a user from an ID token.
147 * @return array{name: string, email: string, external_id: string}
149 protected function getUserDetails(OidcIdToken $token): array
151 $id = $token->getClaim('sub');
154 'external_id' => $id,
155 'email' => $token->getClaim('email'),
156 'name' => $this->getUserDisplayName($token, $id),
161 * Processes a received access token for a user. Login the user when
162 * they exist, optionally registering them automatically.
164 * @throws OpenIdConnectException
165 * @throws JsonDebugException
166 * @throws UserRegistrationException
167 * @throws StoppedAuthenticationException
169 protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
171 $idTokenText = $accessToken->getIdToken();
172 $idToken = new OidcIdToken(
178 if ($this->config()['dump_user_details']) {
179 throw new JsonDebugException($idToken->getAllClaims());
183 $idToken->validate($settings->clientId);
184 } catch (OidcInvalidTokenException $exception) {
185 throw new OpenIdConnectException("ID token validate failed with error: {$exception->getMessage()}");
188 $userDetails = $this->getUserDetails($idToken);
189 $isLoggedIn = auth()->check();
191 if (empty($userDetails['email'])) {
192 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
196 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
199 $user = $this->registrationService->findOrRegister(
200 $userDetails['name'],
201 $userDetails['email'],
202 $userDetails['external_id']
205 if ($user === null) {
206 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
209 $this->loginService->login($user, 'oidc');
215 * Get the OIDC config from the application.
217 protected function config(): array
219 return config('oidc');