3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\JsonDebugException;
7 use BookStack\Exceptions\SamlException;
8 use BookStack\Exceptions\StoppedAuthenticationException;
9 use BookStack\Exceptions\UserRegistrationException;
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;
24 protected RegistrationService $registrationService;
25 protected LoginService $loginService;
26 protected GroupSyncService $groupSyncService;
28 public function __construct(
29 RegistrationService $registrationService,
30 LoginService $loginService,
31 GroupSyncService $groupSyncService
33 $this->config = config('saml2');
34 $this->registrationService = $registrationService;
35 $this->loginService = $loginService;
36 $this->groupSyncService = $groupSyncService;
40 * Initiate a login flow.
44 public function login(): array
46 $toolKit = $this->getToolkit();
47 $returnRoute = url('/saml2/acs');
50 'url' => $toolKit->login($returnRoute, [], false, false, true),
51 'id' => $toolKit->getLastRequestID(),
56 * Initiate a logout flow.
60 public function logout(User $user): array
62 $toolKit = $this->getToolkit();
63 $returnRoute = url('/');
66 $url = $toolKit->logout(
70 session()->get('saml2_session_index'),
72 Constants::NAMEID_EMAIL_ADDRESS
74 $id = $toolKit->getLastRequestID();
75 } catch (Error $error) {
76 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
80 $this->actionLogout();
85 return ['url' => $url, 'id' => $id];
89 * Process the ACS response from the idp and return the
90 * matching, or new if registration active, user matched to the idp.
91 * Returns null if not authenticated.
94 * @throws SamlException
95 * @throws ValidationError
96 * @throws JsonDebugException
97 * @throws UserRegistrationException
99 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
101 // The SAML2 toolkit expects the response to be within the $_POST superglobal
102 // so we need to manually put it back there at this point.
103 $_POST['SAMLResponse'] = $samlResponse;
104 $toolkit = $this->getToolkit();
105 $toolkit->processResponse($requestId);
106 $errors = $toolkit->getErrors();
108 if (!empty($errors)) {
109 $reason = $toolkit->getLastErrorReason();
110 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
111 $message .= $reason ? "; Reason: {$reason}" : '';
112 throw new Error($message);
115 if (!$toolkit->isAuthenticated()) {
119 $attrs = $toolkit->getAttributes();
120 $id = $toolkit->getNameId();
121 session()->put('saml2_session_index', $toolkit->getSessionIndex());
123 return $this->processLoginCallback($id, $attrs);
127 * Process a response for the single logout service.
131 public function processSlsResponse(?string $requestId): ?string
133 $toolkit = $this->getToolkit();
135 // The $retrieveParametersFromServer in the call below will mean the library will take the query
136 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
137 // value so that the exact encoding format is matched when checking the signature.
138 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
139 // PHP (And most other sensible providers) standardise on uppercase.
140 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
141 $errors = $toolkit->getErrors();
143 if (!empty($errors)) {
145 'Invalid SLS Response: ' . implode(', ', $errors)
149 $this->actionLogout();
155 * Do the required actions to log a user out.
157 protected function actionLogout()
160 session()->invalidate();
164 * Get the metadata for this service provider.
168 public function metadata(): string
170 $toolKit = $this->getToolkit(true);
171 $settings = $toolKit->getSettings();
172 $metadata = $settings->getSPMetadata();
173 $errors = $settings->validateMetadata($metadata);
175 if (!empty($errors)) {
177 'Invalid SP metadata: ' . implode(', ', $errors),
178 Error::METADATA_SP_INVALID
186 * Load the underlying Onelogin SAML2 toolkit.
191 protected function getToolkit(bool $spOnly = false): Auth
193 $settings = $this->config['onelogin'];
194 $overrides = $this->config['onelogin_overrides'] ?? [];
196 if ($overrides && is_string($overrides)) {
197 $overrides = json_decode($overrides, true);
200 $metaDataSettings = [];
201 if (!$spOnly && $this->config['autoload_from_metadata']) {
202 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
205 $spSettings = $this->loadOneloginServiceProviderDetails();
206 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
208 return new Auth($settings, $spOnly);
212 * Load dynamic service provider options required by the onelogin toolkit.
214 protected function loadOneloginServiceProviderDetails(): array
217 'entityId' => url('/saml2/metadata'),
218 'assertionConsumerService' => [
219 'url' => url('/saml2/acs'),
221 'singleLogoutService' => [
222 'url' => url('/saml2/sls'),
227 'baseurl' => url('/saml2'),
233 * Check if groups should be synced.
235 protected function shouldSyncGroups(): bool
237 return $this->config['user_to_groups'] !== false;
241 * Calculate the display name.
243 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
245 $displayNameAttr = $this->config['display_name_attributes'];
248 foreach ($displayNameAttr as $dnAttr) {
249 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
250 if ($dnComponent !== null) {
251 $displayName[] = $dnComponent;
255 if (count($displayName) == 0) {
256 $displayName = $defaultValue;
258 $displayName = implode(' ', $displayName);
265 * Get the value to use as the external id saved in BookStack
266 * used to link the user to an existing BookStack DB user.
268 protected function getExternalId(array $samlAttributes, string $defaultValue)
270 $userNameAttr = $this->config['external_id_attribute'];
271 if ($userNameAttr === null) {
272 return $defaultValue;
275 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
279 * Extract the details of a user from a SAML response.
281 * @return array{external_id: string, name: string, email: string, saml_id: string}
283 protected function getUserDetails(string $samlID, $samlAttributes): array
285 $emailAttr = $this->config['email_attribute'];
286 $externalId = $this->getExternalId($samlAttributes, $samlID);
288 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
289 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
292 'external_id' => $externalId,
293 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
295 'saml_id' => $samlID,
300 * Get the groups a user is a part of from the SAML response.
302 public function getUserGroups(array $samlAttributes): array
304 $groupsAttr = $this->config['group_attribute'];
305 $userGroups = $samlAttributes[$groupsAttr] ?? null;
307 if (!is_array($userGroups)) {
315 * For an array of strings, return a default for an empty array,
316 * a string for an array with one element and the full array for
317 * more than one element.
319 protected function simplifyValue(array $data, $defaultValue)
321 switch (count($data)) {
323 $data = $defaultValue;
334 * Get a property from an SAML response.
335 * Handles properties potentially being an array.
337 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
339 if (isset($samlAttributes[$propertyKey])) {
340 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
343 return $defaultValue;
347 * Process the SAML response for a user. Login the user when
348 * they exist, optionally registering them automatically.
350 * @throws SamlException
351 * @throws JsonDebugException
352 * @throws UserRegistrationException
353 * @throws StoppedAuthenticationException
355 public function processLoginCallback(string $samlID, array $samlAttributes): User
357 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
358 $isLoggedIn = auth()->check();
360 if ($this->config['dump_user_details']) {
361 throw new JsonDebugException([
362 'id_from_idp' => $samlID,
363 'attrs_from_idp' => $samlAttributes,
364 'attrs_after_parsing' => $userDetails,
368 if ($userDetails['email'] === null) {
369 throw new SamlException(trans('errors.saml_no_email_address'));
373 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
376 $user = $this->registrationService->findOrRegister(
377 $userDetails['name'],
378 $userDetails['email'],
379 $userDetails['external_id']
382 if ($user === null) {
383 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
386 if ($this->shouldSyncGroups()) {
387 $groups = $this->getUserGroups($samlAttributes);
388 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
391 $this->loginService->login($user, 'saml2');