]> BookStack Code Mirror - bookstack/blob - app/Access/Oidc/OidcService.php
Merge branch 'fix/oidc-logout' into development
[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         // OIDC Logout Feature: Temporarily save token in session 
221         $access_token_for_logout = $idTokenText;
222         session()->put("oidctoken", $access_token_for_logout);
223
224
225
226         $returnClaims = Theme::dispatch(ThemeEvents::OIDC_ID_TOKEN_PRE_VALIDATE, $idToken->getAllClaims(), [
227             'access_token' => $accessToken->getToken(),
228             'expires_in' => $accessToken->getExpires(),
229             'refresh_token' => $accessToken->getRefreshToken(),
230         ]);
231
232         if (!is_null($returnClaims)) {
233             $idToken->replaceClaims($returnClaims);
234         }
235
236         if ($this->config()['dump_user_details']) {
237             throw new JsonDebugException($idToken->getAllClaims());
238         }
239
240         try {
241             $idToken->validate($settings->clientId);
242         } catch (OidcInvalidTokenException $exception) {
243             throw new OidcException("ID token validate failed with error: {$exception->getMessage()}");
244         }
245
246         $userDetails = $this->getUserDetails($idToken);
247         $isLoggedIn = auth()->check();
248
249         if (empty($userDetails['email'])) {
250             throw new OidcException(trans('errors.oidc_no_email_address'));
251         }
252
253         if ($isLoggedIn) {
254             throw new OidcException(trans('errors.oidc_already_logged_in'));
255         }
256
257         try {
258             $user = $this->registrationService->findOrRegister(
259                 $userDetails['name'],
260                 $userDetails['email'],
261                 $userDetails['external_id']
262             );
263         } catch (UserRegistrationException $exception) {
264             throw new OidcException($exception->getMessage());
265         }
266
267         if ($this->shouldSyncGroups()) {
268             $groups = $userDetails['groups'];
269             $detachExisting = $this->config()['remove_from_groups'];
270             $this->groupService->syncUserWithFoundGroups($user, $groups, $detachExisting);
271         }
272
273         $this->loginService->login($user, 'oidc');
274
275         return $user;
276     }
277
278     /**
279      * Get the OIDC config from the application.
280      */
281     protected function config(): array
282     {
283         return config('oidc');
284     }
285
286     /**
287      * Check if groups should be synced.
288      */
289     protected function shouldSyncGroups(): bool
290     {
291         return $this->config()['user_to_groups'] !== false;
292     }
293
294
295     /**
296      * OIDC Logout Feature: Initiate a logout flow.
297      *
298      * @throws OidcException
299      *
300      * @return string
301      */
302     public function logout() {
303
304         $config = $this->config();
305         $app_url = env('APP_URL', '');
306         $end_session_endpoint = $config["end_session_endpoint"];
307
308         $oidctoken = session()->get("oidctoken");
309         session()->invalidate();
310
311         if (str_contains($app_url, 'https://')) { 
312              $protocol = 'https://';
313         } else {
314              $protocol = 'http://';
315         }
316
317
318
319         return redirect($end_session_endpoint.'?id_token_hint='.$oidctoken."&post_logout_redirect_uri=".$protocol.$_SERVER['HTTP_HOST']."/");
320
321
322     }
323
324
325
326 }