]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Oidc: Properly query the UserInfo Endpoint
[bookstack] / app / Access / Oidc / OidcService.php
1 <?php
2
3 namespace BookStack\Access\Oidc;
4
5 use BookStack\Access\GroupSyncService;
6 use BookStack\Access\LoginService;
7 use BookStack\Access\RegistrationService;
8 use BookStack\Exceptions\JsonDebugException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Facades\Theme;
12 use BookStack\Http\HttpRequestService;
13 use BookStack\Theming\ThemeEvents;
14 use BookStack\Users\Models\User;
15 use Illuminate\Support\Arr;
16 use Illuminate\Support\Facades\Cache;
17 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
18 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
19
20 /**
21  * Class OpenIdConnectService
22  * Handles any app-specific OIDC tasks.
23  */
24 class OidcService
25 {
26     public function __construct(
27         protected RegistrationService $registrationService,
28         protected LoginService $loginService,
29         protected HttpRequestService $http,
30         protected GroupSyncService $groupService
31     ) {
32     }
33
34     /**
35      * Initiate an authorization flow.
36      *
37      * @throws OidcException
38      *
39      * @return array{url: string, state: string}
40      */
41     public function login(): array
42     {
43         $settings = $this->getProviderSettings();
44         $provider = $this->getProvider($settings);
45         return [
46             'url'   => $provider->getAuthorizationUrl(),
47             'state' => $provider->getState(),
48         ];
49     }
50
51     /**
52      * Process the Authorization response from the authorization server and
53      * return the matching, or new if registration active, user matched to the
54      * authorization server. Throws if the user cannot be auth if not authenticated.
55      *
56      * @throws JsonDebugException
57      * @throws OidcException
58      * @throws StoppedAuthenticationException
59      * @throws IdentityProviderException
60      */
61     public function processAuthorizeResponse(?string $authorizationCode): User
62     {
63         $settings = $this->getProviderSettings();
64         $provider = $this->getProvider($settings);
65
66         // Try to exchange authorization code for access token
67         $accessToken = $provider->getAccessToken('authorization_code', [
68             'code' => $authorizationCode,
69         ]);
70
71         return $this->processAccessTokenCallback($accessToken, $settings);
72     }
73
74     /**
75      * @throws OidcException
76      */
77     protected function getProviderSettings(): OidcProviderSettings
78     {
79         $config = $this->config();
80         $settings = new OidcProviderSettings([
81             'issuer'                => $config['issuer'],
82             'clientId'              => $config['client_id'],
83             'clientSecret'          => $config['client_secret'],
84             'redirectUri'           => url('/oidc/callback'),
85             'authorizationEndpoint' => $config['authorization_endpoint'],
86             'tokenEndpoint'         => $config['token_endpoint'],
87             'endSessionEndpoint'    => is_string($config['end_session_endpoint']) ? $config['end_session_endpoint'] : null,
88             'userinfoEndpoint'      => $config['userinfo_endpoint'],
89         ]);
90
91         // Use keys if configured
92         if (!empty($config['jwt_public_key'])) {
93             $settings->keys = [$config['jwt_public_key']];
94         }
95
96         // Run discovery
97         if ($config['discover'] ?? false) {
98             try {
99                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
100             } catch (OidcIssuerDiscoveryException $exception) {
101                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
102             }
103         }
104
105         // Prevent use of RP-initiated logout if specifically disabled
106         // Or force use of a URL if specifically set.
107         if ($config['end_session_endpoint'] === false) {
108             $settings->endSessionEndpoint = null;
109         } else if (is_string($config['end_session_endpoint'])) {
110             $settings->endSessionEndpoint = $config['end_session_endpoint'];
111         }
112
113         $settings->validate();
114
115         return $settings;
116     }
117
118     /**
119      * Load the underlying OpenID Connect Provider.
120      */
121     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
122     {
123         $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
124             'httpClient'     => $this->http->buildClient(5),
125             'optionProvider' => new HttpBasicAuthOptionProvider(),
126         ]);
127
128         foreach ($this->getAdditionalScopes() as $scope) {
129             $provider->addScope($scope);
130         }
131
132         return $provider;
133     }
134
135     /**
136      * Get any user-defined addition/custom scopes to apply to the authentication request.
137      *
138      * @return string[]
139      */
140     protected function getAdditionalScopes(): array
141     {
142         $scopeConfig = $this->config()['additional_scopes'] ?: '';
143
144         $scopeArr = explode(',', $scopeConfig);
145         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
146
147         return array_filter($scopeArr);
148     }
149
150     /**
151      * Calculate the display name.
152      */
153     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
154     {
155         $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
156         $displayNameAttrs = explode('|', $displayNameAttrString);
157
158         $displayName = [];
159         foreach ($displayNameAttrs as $dnAttr) {
160             $dnComponent = $token->getClaim($dnAttr) ?? '';
161             if ($dnComponent !== '') {
162                 $displayName[] = $dnComponent;
163             }
164         }
165
166         if (count($displayName) == 0) {
167             $displayName[] = $defaultValue;
168         }
169
170         return implode(' ', $displayName);
171     }
172
173     /**
174      * Extract the assigned groups from the id token.
175      *
176      * @return string[]
177      */
178     protected function getUserGroups(OidcIdToken $token): array
179     {
180         $groupsAttr = $this->config()['groups_claim'];
181         if (empty($groupsAttr)) {
182             return [];
183         }
184
185         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
186         if (!is_array($groupsList)) {
187             return [];
188         }
189
190         return array_values(array_filter($groupsList, function ($val) {
191             return is_string($val);
192         }));
193     }
194
195     /**
196      * Extract the details of a user from an ID token.
197      *
198      * @return array{name: string, email: string, external_id: string, groups: string[]}
199      */
200     protected function getUserDetails(OidcIdToken $token): array
201     {
202         $idClaim = $this->config()['external_id_claim'];
203         $id = $token->getClaim($idClaim);
204
205         return [
206             'external_id' => $id,
207             'email'       => $token->getClaim('email'),
208             'name'        => $this->getUserDisplayName($token, $id),
209             'groups'      => $this->getUserGroups($token),
210         ];
211     }
212
213     /**
214      * Processes a received access token for a user. Login the user when
215      * they exist, optionally registering them automatically.
216      *
217      * @throws OidcException
218      * @throws JsonDebugException
219      * @throws StoppedAuthenticationException
220      */
221     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
222     {
223         $idTokenText = $accessToken->getIdToken();
224         $idToken = new OidcIdToken(
225             $idTokenText,
226             $settings->issuer,
227             $settings->keys,
228         );
229
230         session()->put("oidc_id_token", $idTokenText);
231
232         if (!empty($settings->userinfoEndpoint)) {
233             $provider = $this->getProvider($settings);
234             $request = $provider->getAuthenticatedRequest('GET', $settings->userinfoEndpoint, $accessToken->getToken());
235             $response = $provider->getParsedResponse($request);
236             $claims = $idToken->getAllClaims();
237             foreach ($response as $key => $value) {
238                 $claims[$key] = $value;
239             }
240             $idToken->replaceClaims($claims);
241         }
242
243         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
244             'access_token' => $accessToken->getToken(),
245             'expires_in' => $accessToken->getExpires(),
246             'refresh_token' => $accessToken->getRefreshToken(),
247         ]);
248
249         if (!is_null($returnClaims)) {
250             $idToken->replaceClaims($returnClaims);
251         }
252
253         if ($this->config()['dump_user_details']) {
254             throw new JsonDebugException($idToken->getAllClaims());
255         }
256
257         try {
258             $idToken->validate($settings->clientId);
259         } catch (OidcInvalidTokenException $exception) {
260             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
261         }
262
263         $userDetails = $this->getUserDetails($idToken);
264         $isLoggedIn = auth()->check();
265
266         if (empty($userDetails['email'])) {
267             throw new OidcException(trans('errors.oidc_no_email_address'));
268         }
269
270         if ($isLoggedIn) {
271             throw new OidcException(trans('errors.oidc_already_logged_in'));
272         }
273
274         try {
275             $user = $this->registrationService->findOrRegister(
276                 $userDetails['name'],
277                 $userDetails['email'],
278                 $userDetails['external_id']
279             );
280         } catch (UserRegistrationException $exception) {
281             throw new OidcException($exception->getMessage());
282         }
283
284         if ($this->shouldSyncGroups()) {
285             $groups = $userDetails['groups'];
286             $detachExisting = $this->config()['remove_from_groups'];
287             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
288         }
289
290         $this->loginService->login($user, 'oidc');
291
292         return $user;
293     }
294
295     /**
296      * Get the OIDC config from the application.
297      */
298     protected function config(): array
299     {
300         return config('oidc');
301     }
302
303     /**
304      * Check if groups should be synced.
305      */
306     protected function shouldSyncGroups(): bool
307     {
308         return $this->config()['user_to_groups'] !== false;
309     }
310
311     /**
312      * Start the RP-initiated logout flow if active, otherwise start a standard logout flow.
313      * Returns a post-app-logout redirect URL.
314      * Reference: https://openid.net/specs/openid-connect-rpinitiated-1_0.html
315      * @throws OidcException
316      */
317     public function logout(): string
318     {
319         $oidcToken = session()->pull("oidc_id_token");
320         $defaultLogoutUrl = url($this->loginService->logout());
321         $oidcSettings = $this->getProviderSettings();
322
323         if (!$oidcSettings->endSessionEndpoint) {
324             return $defaultLogoutUrl;
325         }
326
327         $endpointParams = [
328             'id_token_hint' => $oidcToken,
329             'post_logout_redirect_uri' => $defaultLogoutUrl,
330         ];
331
332         $joiner = str_contains($oidcSettings->endSessionEndpoint, '?') ? '&' : '?';
333
334         return $oidcSettings->endSessionEndpoint . $joiner . http_build_query($endpointParams);
335     }
336 }