]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Oidc/OidcService.php
Fix timestamp in API docs example response
[bookstack] / app / Auth / Access / Oidc / OidcService.php
1 <?php
2
3 namespace BookStack\Auth\Access\Oidc;
4
5 use BookStack\Auth\Access\GroupSyncService;
6 use BookStack\Auth\Access\LoginService;
7 use BookStack\Auth\Access\RegistrationService;
8 use BookStack\Auth\User;
9 use BookStack\Exceptions\JsonDebugException;
10 use BookStack\Exceptions\StoppedAuthenticationException;
11 use BookStack\Exceptions\UserRegistrationException;
12 use Illuminate\Support\Arr;
13 use Illuminate\Support\Facades\Cache;
14 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
15 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
16 use Psr\Http\Client\ClientInterface as HttpClient;
17
18 /**
19  * Class OpenIdConnectService
20  * Handles any app-specific OIDC tasks.
21  */
22 class OidcService
23 {
24     protected RegistrationService $registrationService;
25     protected LoginService $loginService;
26     protected HttpClient $httpClient;
27     protected GroupSyncService $groupService;
28
29     /**
30      * OpenIdService constructor.
31      */
32     public function __construct(
33         RegistrationService $registrationService,
34         LoginService $loginService,
35         HttpClient $httpClient,
36         GroupSyncService $groupService
37     ) {
38         $this->registrationService = $registrationService;
39         $this->loginService = $loginService;
40         $this->httpClient = $httpClient;
41         $this->groupService = $groupService;
42     }
43
44     /**
45      * Initiate an authorization flow.
46      *
47      * @throws OidcException
48      *
49      * @return array{url: string, state: string}
50      */
51     public function login(): array
52     {
53         $settings = $this->getProviderSettings();
54         $provider = $this->getProvider($settings);
55         return [
56             'url'   => $provider->getAuthorizationUrl(),
57             'state' => $provider->getState(),
58         ];
59     }
60
61     /**
62      * Process the Authorization response from the authorization server and
63      * return the matching, or new if registration active, user matched to the
64      * authorization server. Throws if the user cannot be auth if not authenticated.
65      *
66      * @throws JsonDebugException
67      * @throws OidcException
68      * @throws StoppedAuthenticationException
69      * @throws IdentityProviderException
70      */
71     public function processAuthorizeResponse(?string $authorizationCode): User
72     {
73         $settings = $this->getProviderSettings();
74         $provider = $this->getProvider($settings);
75
76         // Try to exchange authorization code for access token
77         $accessToken = $provider->getAccessToken('authorization_code', [
78             'code' => $authorizationCode,
79         ]);
80
81         return $this->processAccessTokenCallback($accessToken, $settings);
82     }
83
84     /**
85      * @throws OidcException
86      */
87     protected function getProviderSettings(): OidcProviderSettings
88     {
89         $config = $this->config();
90         $settings = new OidcProviderSettings([
91             'issuer'                => $config['issuer'],
92             'clientId'              => $config['client_id'],
93             'clientSecret'          => $config['client_secret'],
94             'redirectUri'           => url('/oidc/callback'),
95             'authorizationEndpoint' => $config['authorization_endpoint'],
96             'tokenEndpoint'         => $config['token_endpoint'],
97         ]);
98
99         // Use keys if configured
100         if (!empty($config['jwt_public_key'])) {
101             $settings->keys = [$config['jwt_public_key']];
102         }
103
104         // Run discovery
105         if ($config['discover'] ?? false) {
106             try {
107                 $settings->discoverFromIssuer($this->httpClient, Cache::store(null), 15);
108             } catch (OidcIssuerDiscoveryException $exception) {
109                 throw new OidcException('OIDC Discovery Error: ' . $exception->getMessage());
110             }
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->httpClient,
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         $displayNameAttr = $this->config()['display_name_claims'];
156
157         $displayName = [];
158         foreach ($displayNameAttr as $dnAttr) {
159             $dnComponent = $token->getClaim($dnAttr) ?? '';
160             if ($dnComponent !== '') {
161                 $displayName[] = $dnComponent;
162             }
163         }
164
165         if (count($displayName) == 0) {
166             $displayName[] = $defaultValue;
167         }
168
169         return implode(' ', $displayName);
170     }
171
172     /**
173      * Extract the assigned groups from the id token.
174      *
175      * @return string[]
176      */
177     protected function getUserGroups(OidcIdToken $token): array
178     {
179         $groupsAttr = $this->config()['groups_claim'];
180         if (empty($groupsAttr)) {
181             return [];
182         }
183
184         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
185         if (!is_array($groupsList)) {
186             return [];
187         }
188
189         return array_values(array_filter($groupsList, function ($val) {
190             return is_string($val);
191         }));
192     }
193
194     /**
195      * Extract the details of a user from an ID token.
196      *
197      * @return array{name: string, email: string, external_id: string, groups: string[]}
198      */
199     protected function getUserDetails(OidcIdToken $token): array
200     {
201         $idClaim = $this->config()['external_id_claim'];
202         $id = $token->getClaim($idClaim);
203
204         return [
205             'external_id' => $id,
206             'email'       => $token->getClaim('email'),
207             'name'        => $this->getUserDisplayName($token, $id),
208             'groups'      => $this->getUserGroups($token),
209         ];
210     }
211
212     /**
213      * Processes a received access token for a user. Login the user when
214      * they exist, optionally registering them automatically.
215      *
216      * @throws OidcException
217      * @throws JsonDebugException
218      * @throws StoppedAuthenticationException
219      */
220     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
221     {
222         $idTokenText = $accessToken->getIdToken();
223         $idToken = new OidcIdToken(
224             $idTokenText,
225             $settings->issuer,
226             $settings->keys,
227         );
228
229         if ($this->config()['dump_user_details']) {
230             throw new JsonDebugException($idToken->getAllClaims());
231         }
232
233         try {
234             $idToken->validate($settings->clientId);
235         } catch (OidcInvalidTokenException $exception) {
236             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
237         }
238
239         $userDetails = $this->getUserDetails($idToken);
240         $isLoggedIn = auth()->check();
241
242         if (empty($userDetails['email'])) {
243             throw new OidcException(trans('errors.oidc_no_email_address'));
244         }
245
246         if ($isLoggedIn) {
247             throw new OidcException(trans('errors.oidc_already_logged_in'));
248         }
249
250         try {
251             $user = $this->registrationService->findOrRegister(
252                 $userDetails['name'],
253                 $userDetails['email'],
254                 $userDetails['external_id']
255             );
256         } catch (UserRegistrationException $exception) {
257             throw new OidcException($exception->getMessage());
258         }
259
260         if ($this->shouldSyncGroups()) {
261             $groups = $userDetails['groups'];
262             $detachExisting = $this->config()['remove_from_groups'];
263             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
264         }
265
266         $this->loginService->login($user, 'oidc');
267
268         return $user;
269     }
270
271     /**
272      * Get the OIDC config from the application.
273      */
274     protected function config(): array
275     {
276         return config('oidc');
277     }
278
279     /**
280      * Check if groups should be synced.
281      */
282     protected function shouldSyncGroups(): bool
283     {
284         return $this->config()['user_to_groups'] !== false;
285     }
286 }