1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\OpenIdConnectException;
6 use BookStack\Exceptions\StoppedAuthenticationException;
7 use BookStack\Exceptions\UserRegistrationException;
9 use Lcobucci\JWT\Signer\Rsa\Sha256;
10 use Lcobucci\JWT\Token;
11 use OpenIDConnectClient\AccessToken;
12 use OpenIDConnectClient\OpenIDConnectProvider;
15 * Class OpenIdConnectService
16 * Handles any app-specific OIDC tasks.
18 class OpenIdConnectService
20 protected $registrationService;
21 protected $loginService;
25 * OpenIdService constructor.
27 public function __construct(RegistrationService $registrationService, LoginService $loginService)
29 $this->config = config('oidc');
30 $this->registrationService = $registrationService;
31 $this->loginService = $loginService;
35 * Initiate an authorization flow.
36 * @return array{url: string, state: string}
38 public function login(): array
40 $provider = $this->getProvider();
42 'url' => $provider->getAuthorizationUrl(),
43 'state' => $provider->getState(),
48 * Process the Authorization response from the authorization server and
49 * return the matching, or new if registration active, user matched to
50 * the authorization server.
51 * Returns null if not authenticated.
54 public function processAuthorizeResponse(?string $authorizationCode): ?User
56 $provider = $this->getProvider();
58 // Try to exchange authorization code for access token
59 $accessToken = $provider->getAccessToken('authorization_code', [
60 'code' => $authorizationCode,
63 return $this->processAccessTokenCallback($accessToken);
67 * Load the underlying OpenID Connect Provider.
69 protected function getProvider(): OpenIDConnectProvider
73 'clientId' => $this->config['client_id'],
74 'clientSecret' => $this->config['client_secret'],
75 'idTokenIssuer' => $this->config['issuer'],
76 'redirectUri' => url('/oidc/redirect'),
77 'urlAuthorize' => $this->config['authorization_endpoint'],
78 'urlAccessToken' => $this->config['token_endpoint'],
79 'urlResourceOwnerDetails' => null,
80 'publicKey' => $this->config['jwt_public_key'],
81 'scopes' => 'profile email',
86 'signer' => new Sha256(),
89 return new OpenIDConnectProvider($settings, $services);
93 * Calculate the display name
95 protected function getUserDisplayName(Token $token, string $defaultValue): string
97 $displayNameAttr = $this->config['display_name_claims'];
100 foreach ($displayNameAttr as $dnAttr) {
101 $dnComponent = $token->claims()->get($dnAttr, '');
102 if ($dnComponent !== '') {
103 $displayName[] = $dnComponent;
107 if (count($displayName) == 0) {
108 $displayName[] = $defaultValue;
111 return implode(' ', $displayName);
115 * Extract the details of a user from an ID token.
116 * @return array{name: string, email: string, external_id: string}
118 protected function getUserDetails(Token $token): array
120 $id = $token->claims()->get('sub');
122 'external_id' => $id,
123 'email' => $token->claims()->get('email'),
124 'name' => $this->getUserDisplayName($token, $id),
129 * Processes a received access token for a user. Login the user when
130 * they exist, optionally registering them automatically.
131 * @throws OpenIdConnectException
132 * @throws JsonDebugException
133 * @throws UserRegistrationException
134 * @throws StoppedAuthenticationException
136 protected function processAccessTokenCallback(AccessToken $accessToken): User
138 $userDetails = $this->getUserDetails($accessToken->getIdToken());
139 $isLoggedIn = auth()->check();
141 if ($this->config['dump_user_details']) {
142 throw new JsonDebugException($accessToken->jsonSerialize());
145 if ($userDetails['email'] === null) {
146 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
150 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
153 $user = $this->registrationService->findOrRegister(
154 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
157 if ($user === null) {
158 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
161 $this->loginService->login($user, 'oidc');