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\Token;
10 use League\OAuth2\Client\Token\AccessToken;
13 * Class OpenIdConnectService
14 * Handles any app-specific OIDC tasks.
16 class OpenIdConnectService
18 protected $registrationService;
19 protected $loginService;
23 * OpenIdService constructor.
25 public function __construct(RegistrationService $registrationService, LoginService $loginService)
27 $this->config = config('oidc');
28 $this->registrationService = $registrationService;
29 $this->loginService = $loginService;
33 * Initiate an authorization flow.
34 * @return array{url: string, state: string}
36 public function login(): array
38 $provider = $this->getProvider();
40 'url' => $provider->getAuthorizationUrl(),
41 'state' => $provider->getState(),
46 * Process the Authorization response from the authorization server and
47 * return the matching, or new if registration active, user matched to
48 * the authorization server.
49 * Returns null if not authenticated.
52 public function processAuthorizeResponse(?string $authorizationCode): ?User
54 $provider = $this->getProvider();
56 // Try to exchange authorization code for access token
57 $accessToken = $provider->getAccessToken('authorization_code', [
58 'code' => $authorizationCode,
61 return $this->processAccessTokenCallback($accessToken);
65 * Load the underlying OpenID Connect Provider.
67 protected function getProvider(): OpenIdConnectOAuthProvider
71 'clientId' => $this->config['client_id'],
72 'clientSecret' => $this->config['client_secret'],
73 'redirectUri' => url('/oidc/redirect'),
74 'authorizationEndpoint' => $this->config['authorization_endpoint'],
75 'tokenEndpoint' => $this->config['token_endpoint'],
78 return new OpenIdConnectOAuthProvider($settings);
82 * Calculate the display name
84 protected function getUserDisplayName(Token $token, string $defaultValue): string
86 $displayNameAttr = $this->config['display_name_claims'];
89 foreach ($displayNameAttr as $dnAttr) {
90 $dnComponent = $token->claims()->get($dnAttr, '');
91 if ($dnComponent !== '') {
92 $displayName[] = $dnComponent;
96 if (count($displayName) == 0) {
97 $displayName[] = $defaultValue;
100 return implode(' ', $displayName);
104 * Extract the details of a user from an ID token.
105 * @return array{name: string, email: string, external_id: string}
107 protected function getUserDetails(Token $token): array
109 $id = $token->claims()->get('sub');
111 'external_id' => $id,
112 'email' => $token->claims()->get('email'),
113 'name' => $this->getUserDisplayName($token, $id),
118 * Processes a received access token for a user. Login the user when
119 * they exist, optionally registering them automatically.
120 * @throws OpenIdConnectException
121 * @throws JsonDebugException
122 * @throws UserRegistrationException
123 * @throws StoppedAuthenticationException
125 protected function processAccessTokenCallback(AccessToken $accessToken): User
127 dd($accessToken->getValues());
128 // TODO - Create a class to manage token parsing and validation on this
129 // Using the config params:
130 // $this->config['jwt_public_key']
131 // $this->config['issuer']
133 // Ensure ID token validation is done:
134 // https://openid.net/specs/openid-connect-basic-1_0.html#IDTokenValidation
135 // To full affect and tested
137 $userDetails = $this->getUserDetails($accessToken->getIdToken());
138 $isLoggedIn = auth()->check();
140 if ($this->config['dump_user_details']) {
141 throw new JsonDebugException($accessToken->jsonSerialize());
144 if ($userDetails['email'] === null) {
145 throw new OpenIdConnectException(trans('errors.oidc_no_email_address'));
149 throw new OpenIdConnectException(trans('errors.oidc_already_logged_in'), '/login');
152 $user = $this->registrationService->findOrRegister(
153 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
156 if ($user === null) {
157 throw new OpenIdConnectException(trans('errors.oidc_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
160 $this->loginService->login($user, 'oidc');