]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Editors: Properly aligned edit area border radius
[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         ]);
88
89         // Use keys if configured
90         if (!empty($config['jwt_public_key'])) {
91             $settings->keys = [$config['jwt_public_key']];
92         }
93
94         // Run discovery
95         if ($config['discover'] ?? false) {
96             try {
97                 $settings->discoverFromIssuer($this->http->buildClient(5), Cache::store(null), 15);
98             } catch (OidcIssuerDiscoveryException $exception) {
99                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
100             }
101         }
102
103         $settings->validate();
104
105         return $settings;
106     }
107
108     /**
109      * Load the underlying OpenID Connect Provider.
110      */
111     protected function getProvider(OidcProviderSettings $settings): OidcOAuthProvider
112     {
113         $provider = new OidcOAuthProvider($settings->arrayForProvider(), [
114             'httpClient'     => $this->http->buildClient(5),
115             'optionProvider' => new HttpBasicAuthOptionProvider(),
116         ]);
117
118         foreach ($this->getAdditionalScopes() as $scope) {
119             $provider->addScope($scope);
120         }
121
122         return $provider;
123     }
124
125     /**
126      * Get any user-defined addition/custom scopes to apply to the authentication request.
127      *
128      * @return string[]
129      */
130     protected function getAdditionalScopes(): array
131     {
132         $scopeConfig = $this->config()['additional_scopes'] ?: '';
133
134         $scopeArr = explode(',', $scopeConfig);
135         $scopeArr = array_map(fn (string $scope) => trim($scope), $scopeArr);
136
137         return array_filter($scopeArr);
138     }
139
140     /**
141      * Calculate the display name.
142      */
143     protected function getUserDisplayName(OidcIdToken $token, string $defaultValue): string
144     {
145         $displayNameAttrString = $this->config()['display_name_claims'] ?? '';
146         $displayNameAttrs = explode('|', $displayNameAttrString);
147
148         $displayName = [];
149         foreach ($displayNameAttrs as $dnAttr) {
150             $dnComponent = $token->getClaim($dnAttr) ?? '';
151             if ($dnComponent !== '') {
152                 $displayName[] = $dnComponent;
153             }
154         }
155
156         if (count($displayName) == 0) {
157             $displayName[] = $defaultValue;
158         }
159
160         return implode(' ', $displayName);
161     }
162
163     /**
164      * Extract the assigned groups from the id token.
165      *
166      * @return string[]
167      */
168     protected function getUserGroups(OidcIdToken $token): array
169     {
170         $groupsAttr = $this->config()['groups_claim'];
171         if (empty($groupsAttr)) {
172             return [];
173         }
174
175         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
176         if (!is_array($groupsList)) {
177             return [];
178         }
179
180         return array_values(array_filter($groupsList, function ($val) {
181             return is_string($val);
182         }));
183     }
184
185     /**
186      * Extract the details of a user from an ID token.
187      *
188      * @return array{name: string, email: string, external_id: string, groups: string[]}
189      */
190     protected function getUserDetails(OidcIdToken $token): array
191     {
192         $idClaim = $this->config()['external_id_claim'];
193         $id = $token->getClaim($idClaim);
194
195         return [
196             'external_id' => $id,
197             'email'       => $token->getClaim('email'),
198             'name'        => $this->getUserDisplayName($token, $id),
199             'groups'      => $this->getUserGroups($token),
200         ];
201     }
202
203     /**
204      * Processes a received access token for a user. Login the user when
205      * they exist, optionally registering them automatically.
206      *
207      * @throws OidcException
208      * @throws JsonDebugException
209      * @throws StoppedAuthenticationException
210      */
211     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
212     {
213         $idTokenText = $accessToken->getIdToken();
214         $idToken = new OidcIdToken(
215             $idTokenText,
216             $settings->issuer,
217             $settings->keys,
218         );
219
220         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
221             'access_token' => $accessToken->getToken(),
222             'expires_in' => $accessToken->getExpires(),
223             'refresh_token' => $accessToken->getRefreshToken(),
224         ]);
225
226         if (!is_null($returnClaims)) {
227             $idToken->replaceClaims($returnClaims);
228         }
229
230         if ($this->config()['dump_user_details']) {
231             throw new JsonDebugException($idToken->getAllClaims());
232         }
233
234         try {
235             $idToken->validate($settings->clientId);
236         } catch (OidcInvalidTokenException $exception) {
237             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
238         }
239
240         $userDetails = $this->getUserDetails($idToken);
241         $isLoggedIn = auth()->check();
242
243         if (empty($userDetails['email'])) {
244             throw new OidcException(trans('errors.oidc_no_email_address'));
245         }
246
247         if ($isLoggedIn) {
248             throw new OidcException(trans('errors.oidc_already_logged_in'));
249         }
250
251         try {
252             $user = $this->registrationService->findOrRegister(
253                 $userDetails['name'],
254                 $userDetails['email'],
255                 $userDetails['external_id']
256             );
257         } catch (UserRegistrationException $exception) {
258             throw new OidcException($exception->getMessage());
259         }
260
261         if ($this->shouldSyncGroups()) {
262             $groups = $userDetails['groups'];
263             $detachExisting = $this->config()['remove_from_groups'];
264             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
265         }
266
267         $this->loginService->login($user, 'oidc');
268
269         return $user;
270     }
271
272     /**
273      * Get the OIDC config from the application.
274      */
275     protected function config(): array
276     {
277         return config('oidc');
278     }
279
280     /**
281      * Check if groups should be synced.
282      */
283     protected function shouldSyncGroups(): bool
284     {
285         return $this->config()['user_to_groups'] !== false;
286     }
287 }