3 namespace BookStack\Access;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
7 use BookStack\Exceptions\StoppedAuthenticationException;
8 use BookStack\Exceptions\UserRegistrationException;
9 use BookStack\Users\Models\User;
11 use OneLogin\Saml2\Auth;
12 use OneLogin\Saml2\Constants;
13 use OneLogin\Saml2\Error;
14 use OneLogin\Saml2\IdPMetadataParser;
15 use OneLogin\Saml2\ValidationError;
19 * Handles any app-specific SAML tasks.
23 protected array $config;
25 public function __construct(
26 protected RegistrationService $registrationService,
27 protected LoginService $loginService,
28 protected GroupSyncService $groupSyncService
30 $this->config = config('saml2');
34 * Initiate a login flow.
38 public function login(): array
40 $toolKit = $this->getToolkit();
41 $returnRoute = url('/saml2/acs');
44 'url' => $toolKit->login($returnRoute, [], false, false, true),
45 'id' => $toolKit->getLastRequestID(),
50 * Initiate a logout flow.
51 * Returns the SAML2 request ID, and the URL to redirect the user to.
54 * @returns array{url: string, id: ?string}
56 public function logout(User $user): array
58 $toolKit = $this->getToolkit();
59 $sessionIndex = session()->get('saml2_session_index');
60 $returnUrl = url($this->loginService->logout());
63 $url = $toolKit->logout(
69 Constants::NAMEID_EMAIL_ADDRESS
71 $id = $toolKit->getLastRequestID();
72 } catch (Error $error) {
73 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
81 return ['url' => $url, 'id' => $id];
85 * Process the ACS response from the idp and return the
86 * matching, or new if registration active, user matched to the idp.
87 * Returns null if not authenticated.
90 * @throws SamlException
91 * @throws ValidationError
92 * @throws JsonDebugException
93 * @throws UserRegistrationException
95 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
97 // The SAML2 toolkit expects the response to be within the $_POST superglobal
98 // so we need to manually put it back there at this point.
99 $_POST['SAMLResponse'] = $samlResponse;
100 $toolkit = $this->getToolkit();
101 $toolkit->processResponse($requestId);
102 $errors = $toolkit->getErrors();
104 if (!empty($errors)) {
105 $reason = $toolkit->getLastErrorReason();
106 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
107 $message .= $reason ? "; Reason: {$reason}" : '';
108 throw new Error($message);
111 if (!$toolkit->isAuthenticated()) {
115 $attrs = $toolkit->getAttributes();
116 $id = $toolkit->getNameId();
117 session()->put('saml2_session_index', $toolkit->getSessionIndex());
119 return $this->processLoginCallback($id, $attrs);
123 * Process a response for the single logout service.
127 public function processSlsResponse(?string $requestId): string
129 $toolkit = $this->getToolkit();
131 // The $retrieveParametersFromServer in the call below will mean the library will take the query
132 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
133 // value so that the exact encoding format is matched when checking the signature.
134 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
135 // PHP (And most other sensible providers) standardise on uppercase.
136 $samlRedirect = $toolkit->processSLO(true, $requestId, true, null, true);
137 $errors = $toolkit->getErrors();
139 if (!empty($errors)) {
141 'Invalid SLS Response: ' . implode(', ', $errors)
145 $defaultBookStackRedirect = $this->loginService->logout();
147 return $samlRedirect ?? $defaultBookStackRedirect;
151 * Get the metadata for this service provider.
155 public function metadata(): string
157 $toolKit = $this->getToolkit(true);
158 $settings = $toolKit->getSettings();
159 $metadata = $settings->getSPMetadata();
160 $errors = $settings->validateMetadata($metadata);
162 if (!empty($errors)) {
164 'Invalid SP metadata: ' . implode(', ', $errors),
165 Error::METADATA_SP_INVALID
173 * Load the underlying Onelogin SAML2 toolkit.
178 protected function getToolkit(bool $spOnly = false): Auth
180 $settings = $this->config['onelogin'];
181 $overrides = $this->config['onelogin_overrides'] ?? [];
183 if ($overrides && is_string($overrides)) {
184 $overrides = json_decode($overrides, true);
187 $metaDataSettings = [];
188 if (!$spOnly && $this->config['autoload_from_metadata']) {
189 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
192 $spSettings = $this->loadOneloginServiceProviderDetails();
193 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
195 return new Auth($settings, $spOnly);
199 * Load dynamic service provider options required by the onelogin toolkit.
201 protected function loadOneloginServiceProviderDetails(): array
204 'entityId' => url('/saml2/metadata'),
205 'assertionConsumerService' => [
206 'url' => url('/saml2/acs'),
208 'singleLogoutService' => [
209 'url' => url('/saml2/sls'),
214 'baseurl' => url('/saml2'),
220 * Check if groups should be synced.
222 protected function shouldSyncGroups(): bool
224 return $this->config['user_to_groups'] !== false;
228 * Calculate the display name.
230 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
232 $displayNameAttr = $this->config['display_name_attributes'];
235 foreach ($displayNameAttr as $dnAttr) {
236 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
237 if ($dnComponent !== null) {
238 $displayName[] = $dnComponent;
242 if (count($displayName) == 0) {
243 $displayName = $defaultValue;
245 $displayName = implode(' ', $displayName);
252 * Get the value to use as the external id saved in BookStack
253 * used to link the user to an existing BookStack DB user.
255 protected function getExternalId(array $samlAttributes, string $defaultValue)
257 $userNameAttr = $this->config['external_id_attribute'];
258 if ($userNameAttr === null) {
259 return $defaultValue;
262 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
266 * Extract the details of a user from a SAML response.
268 * @return array{external_id: string, name: string, email: string, saml_id: string}
270 protected function getUserDetails(string $samlID, $samlAttributes): array
272 $emailAttr = $this->config['email_attribute'];
273 $externalId = $this->getExternalId($samlAttributes, $samlID);
275 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
276 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
279 'external_id' => $externalId,
280 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
282 'saml_id' => $samlID,
287 * Get the groups a user is a part of from the SAML response.
289 public function getUserGroups(array $samlAttributes): array
291 $groupsAttr = $this->config['group_attribute'];
292 $userGroups = $samlAttributes[$groupsAttr] ?? null;
294 if (!is_array($userGroups)) {
302 * For an array of strings, return a default for an empty array,
303 * a string for an array with one element and the full array for
304 * more than one element.
306 protected function simplifyValue(array $data, $defaultValue)
308 switch (count($data)) {
310 $data = $defaultValue;
321 * Get a property from an SAML response.
322 * Handles properties potentially being an array.
324 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
326 if (isset($samlAttributes[$propertyKey])) {
327 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
330 return $defaultValue;
334 * Process the SAML response for a user. Login the user when
335 * they exist, optionally registering them automatically.
337 * @throws SamlException
338 * @throws JsonDebugException
339 * @throws UserRegistrationException
340 * @throws StoppedAuthenticationException
342 public function processLoginCallback(string $samlID, array $samlAttributes): User
344 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
345 $isLoggedIn = auth()->check();
347 if ($this->shouldSyncGroups()) {
348 $userDetails['groups'] = $this->getUserGroups($samlAttributes);
351 if ($this->config['dump_user_details']) {
352 throw new JsonDebugException([
353 'id_from_idp' => $samlID,
354 'attrs_from_idp' => $samlAttributes,
355 'attrs_after_parsing' => $userDetails,
359 if ($userDetails['email'] === null) {
360 throw new SamlException(trans('errors.saml_no_email_address'));
364 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
367 $user = $this->registrationService->findOrRegister(
368 $userDetails['name'],
369 $userDetails['email'],
370 $userDetails['external_id']
373 if ($this->shouldSyncGroups()) {
374 $this->groupSyncService->syncUserWithFoundGroups($user, $userDetails['groups'], $this->config['remove_from_groups']);
377 $this->loginService->login($user, 'saml2');