]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/Oidc/OidcService.php
Added force option for update-url command
[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 BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
14 use Illuminate\Support\Arr;
15 use Illuminate\Support\Facades\Cache;
16 use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
17 use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
18 use Psr\Http\Client\ClientInterface as HttpClient;
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 HttpClient $httpClient,
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->httpClient, 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->httpClient,
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         $displayNameAttr = $this->config()['display_name_claims'];
146
147         $displayName = [];
148         foreach ($displayNameAttr as $dnAttr) {
149             $dnComponent = $token->getClaim($dnAttr) ?? '';
150             if ($dnComponent !== '') {
151                 $displayName[] = $dnComponent;
152             }
153         }
154
155         if (count($displayName) == 0) {
156             $displayName[] = $defaultValue;
157         }
158
159         return implode(' ', $displayName);
160     }
161
162     /**
163      * Extract the assigned groups from the id token.
164      *
165      * @return string[]
166      */
167     protected function getUserGroups(OidcIdToken $token): array
168     {
169         $groupsAttr = $this->config()['groups_claim'];
170         if (empty($groupsAttr)) {
171             return [];
172         }
173
174         $groupsList = Arr::get($token->getAllClaims(), $groupsAttr);
175         if (!is_array($groupsList)) {
176             return [];
177         }
178
179         return array_values(array_filter($groupsList, function ($val) {
180             return is_string($val);
181         }));
182     }
183
184     /**
185      * Extract the details of a user from an ID token.
186      *
187      * @return array{name: string, email: string, external_id: string, groups: string[]}
188      */
189     protected function getUserDetails(OidcIdToken $token): array
190     {
191         $idClaim = $this->config()['external_id_claim'];
192         $id = $token->getClaim($idClaim);
193
194         return [
195             'external_id' => $id,
196             'email'       => $token->getClaim('email'),
197             'name'        => $this->getUserDisplayName($token, $id),
198             'groups'      => $this->getUserGroups($token),
199         ];
200     }
201
202     /**
203      * Processes a received access token for a user. Login the user when
204      * they exist, optionally registering them automatically.
205      *
206      * @throws OidcException
207      * @throws JsonDebugException
208      * @throws StoppedAuthenticationException
209      */
210     protected function processAccessTokenCallback(OidcAccessToken $accessToken, OidcProviderSettings $settings): User
211     {
212         $idTokenText = $accessToken->getIdToken();
213         $idToken = new OidcIdToken(
214             $idTokenText,
215             $settings->issuer,
216             $settings->keys,
217         );
218
219         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
220             'access_token' => $accessToken->getToken(),
221             'expires_in' => $accessToken->getExpires(),
222             'refresh_token' => $accessToken->getRefreshToken(),
223         ]);
224
225         if (!is_null($returnClaims)) {
226             $idToken->replaceClaims($returnClaims);
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 }