1 <?php namespace BookStack\Auth\Access\OpenIdConnect;
3 use BookStack\Auth\Access\LoginService;
4 use BookStack\Auth\Access\OpenIdConnect\OpenIdConnectOAuthProvider;
5 use BookStack\Auth\Access\RegistrationService;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\JsonDebugException;
8 use BookStack\Exceptions\OpenIdConnectException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
12 use Lcobucci\JWT\Token;
13 use League\OAuth2\Client\Token\AccessToken;
21 * Class OpenIdConnectService
22 * Handles any app-specific OIDC tasks.
24 class OpenIdConnectService
26 protected $registrationService;
27 protected $loginService;
31 * OpenIdService constructor.
33 public function __construct(RegistrationService $registrationService, LoginService $loginService)
35 $this->config = config('oidc');
36 $this->registrationService = $registrationService;
37 $this->loginService = $loginService;
41 * Initiate an authorization flow.
42 * @return array{url: string, state: string}
44 public function login(): array
46 $provider = $this->getProvider();
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.
60 public function processAuthorizeResponse(?string $authorizationCode): ?User
62 $provider = $this->getProvider();
64 // Try to exchange authorization code for access token
65 $accessToken = $provider->getAccessToken('authorization_code', [
66 'code' => $authorizationCode,
69 return $this->processAccessTokenCallback($accessToken);
73 * Load the underlying OpenID Connect Provider.
75 protected function getProvider(): OpenIdConnectOAuthProvider
79 'clientId' => $this->config['client_id'],
80 'clientSecret' => $this->config['client_secret'],
81 'redirectUri' => url('/oidc/redirect'),
82 'authorizationEndpoint' => $this->config['authorization_endpoint'],
83 'tokenEndpoint' => $this->config['token_endpoint'],
86 return new OpenIdConnectOAuthProvider($settings);
90 * Calculate the display name
92 protected function getUserDisplayName(Token $token, string $defaultValue): string
94 $displayNameAttr = $this->config['display_name_claims'];
97 foreach ($displayNameAttr as $dnAttr) {
98 $dnComponent = $token->claims()->get($dnAttr, '');
99 if ($dnComponent !== '') {
100 $displayName[] = $dnComponent;
104 if (count($displayName) == 0) {
105 $displayName[] = $defaultValue;
108 return implode(' ', $displayName);
112 * Extract the details of a user from an ID token.
113 * @return array{name: string, email: string, external_id: string}
115 protected function getUserDetails(Token $token): array
117 $id = $token->claims()->get('sub');
119 'external_id' => $id,
120 'email' => $token->claims()->get('email'),
121 'name' => $this->getUserDisplayName($token, $id),
126 * Processes a received access token for a user. Login the user when
127 * they exist, optionally registering them automatically.
128 * @throws OpenIdConnectException
129 * @throws JsonDebugException
130 * @throws UserRegistrationException
131 * @throws StoppedAuthenticationException
133 protected function processAccessTokenCallback(OpenIdConnectAccessToken $accessToken): User
135 $idTokenText = $accessToken->getIdToken();
136 $idToken = new OpenIdConnectIdToken(
138 $this->config['issuer'],
139 [$this->config['jwt_public_key']]
142 // TODO - Create a class to manage token parsing and validation on this
143 // Ensure ID token validation is done:
144 // https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
145 // To full affect and tested
146 // JWT signature algorthims:
147 // https://datatracker.ietf.org/doc/html/rfc7518#section-3
149 $userDetails = $this->getUserDetails($accessToken->getIdToken());
150 $isLoggedIn = auth()->check();
152 if ($this->config['dump_user_details']) {
153 throw new JsonDebugException($accessToken->jsonSerialize());
156 if ($userDetails['email'] === null) {
157 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
161 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
164 $user = $this->registrationService->findOrRegister(
165 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
168 if ($user === null) {
169 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
172 $this->loginService->login($user, 'oidc');