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.
24 protected $registrationService;
25 protected $loginService;
26 protected $groupSyncService;
29 * Saml2Service constructor.
31 public function __construct(
32 RegistrationService $registrationService,
33 LoginService $loginService,
34 GroupSyncService $groupSyncService
36 $this->config = config('saml2');
37 $this->registrationService = $registrationService;
38 $this->loginService = $loginService;
39 $this->groupSyncService = $groupSyncService;
43 * Initiate a login flow.
47 public function login(): array
49 $toolKit = $this->getToolkit();
50 $returnRoute = url('/saml2/acs');
53 'url' => $toolKit->login($returnRoute, [], false, false, true),
54 'id' => $toolKit->getLastRequestID(),
59 * Initiate a logout flow.
63 public function logout(User $user): array
65 $toolKit = $this->getToolkit();
66 $returnRoute = url('/');
69 $url = $toolKit->logout(
75 Constants::NAMEID_EMAIL_ADDRESS
77 $id = $toolKit->getLastRequestID();
78 } catch (Error $error) {
79 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
83 $this->actionLogout();
88 return ['url' => $url, 'id' => $id];
92 * Process the ACS response from the idp and return the
93 * matching, or new if registration active, user matched to the idp.
94 * Returns null if not authenticated.
97 * @throws SamlException
98 * @throws ValidationError
99 * @throws JsonDebugException
100 * @throws UserRegistrationException
102 public function processAcsResponse(?string $requestId, string $samlResponse): ?User
104 // The SAML2 toolkit expects the response to be within the $_POST superglobal
105 // so we need to manually put it back there at this point.
106 $_POST['SAMLResponse'] = $samlResponse;
107 $toolkit = $this->getToolkit();
108 $toolkit->processResponse($requestId);
109 $errors = $toolkit->getErrors();
111 if (!empty($errors)) {
113 'Invalid ACS Response: ' . implode(', ', $errors)
117 if (!$toolkit->isAuthenticated()) {
121 $attrs = $toolkit->getAttributes();
122 $id = $toolkit->getNameId();
124 return $this->processLoginCallback($id, $attrs);
128 * Process a response for the single logout service.
132 public function processSlsResponse(?string $requestId): ?string
134 $toolkit = $this->getToolkit();
136 // The $retrieveParametersFromServer in the call below will mean the library will take the query
137 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
138 // value so that the exact encoding format is matched when checking the signature.
139 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
140 // PHP (And most other sensible providers) standardise on uppercase.
141 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
142 $errors = $toolkit->getErrors();
144 if (!empty($errors)) {
146 'Invalid SLS Response: ' . implode(', ', $errors)
150 $this->actionLogout();
156 * Do the required actions to log a user out.
158 protected function actionLogout()
161 session()->invalidate();
165 * Get the metadata for this service provider.
169 public function metadata(): string
171 $toolKit = $this->getToolkit();
172 $settings = $toolKit->getSettings();
173 $metadata = $settings->getSPMetadata();
174 $errors = $settings->validateMetadata($metadata);
176 if (!empty($errors)) {
178 'Invalid SP metadata: ' . implode(', ', $errors),
179 Error::METADATA_SP_INVALID
187 * Load the underlying Onelogin SAML2 toolkit.
192 protected function getToolkit(): Auth
194 $settings = $this->config['onelogin'];
195 $overrides = $this->config['onelogin_overrides'] ?? [];
197 if ($overrides && is_string($overrides)) {
198 $overrides = json_decode($overrides, true);
201 $metaDataSettings = [];
202 if ($this->config['autoload_from_metadata']) {
203 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
206 $spSettings = $this->loadOneloginServiceProviderDetails();
207 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
209 return new Auth($settings);
213 * Load dynamic service provider options required by the onelogin toolkit.
215 protected function loadOneloginServiceProviderDetails(): array
218 'entityId' => url('/saml2/metadata'),
219 'assertionConsumerService' => [
220 'url' => url('/saml2/acs'),
222 'singleLogoutService' => [
223 'url' => url('/saml2/sls'),
228 'baseurl' => url('/saml2'),
234 * Check if groups should be synced.
236 protected function shouldSyncGroups(): bool
238 return $this->config['user_to_groups'] !== false;
242 * Calculate the display name.
244 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
246 $displayNameAttr = $this->config['display_name_attributes'];
249 foreach ($displayNameAttr as $dnAttr) {
250 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
251 if ($dnComponent !== null) {
252 $displayName[] = $dnComponent;
256 if (count($displayName) == 0) {
257 $displayName = $defaultValue;
259 $displayName = implode(' ', $displayName);
266 * Get the value to use as the external id saved in BookStack
267 * used to link the user to an existing BookStack DB user.
269 protected function getExternalId(array $samlAttributes, string $defaultValue)
271 $userNameAttr = $this->config['external_id_attribute'];
272 if ($userNameAttr === null) {
273 return $defaultValue;
276 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
280 * Extract the details of a user from a SAML response.
282 * @return array{external_id: string, name: string, email: string, saml_id: string}
284 protected function getUserDetails(string $samlID, $samlAttributes): array
286 $emailAttr = $this->config['email_attribute'];
287 $externalId = $this->getExternalId($samlAttributes, $samlID);
289 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
290 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
293 'external_id' => $externalId,
294 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
296 'saml_id' => $samlID,
301 * Get the groups a user is a part of from the SAML response.
303 public function getUserGroups(array $samlAttributes): array
305 $groupsAttr = $this->config['group_attribute'];
306 $userGroups = $samlAttributes[$groupsAttr] ?? null;
308 if (!is_array($userGroups)) {
316 * For an array of strings, return a default for an empty array,
317 * a string for an array with one element and the full array for
318 * more than one element.
320 protected function simplifyValue(array $data, $defaultValue)
322 switch (count($data)) {
324 $data = $defaultValue;
335 * Get a property from an SAML response.
336 * Handles properties potentially being an array.
338 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
340 if (isset($samlAttributes[$propertyKey])) {
341 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
344 return $defaultValue;
348 * Process the SAML response for a user. Login the user when
349 * they exist, optionally registering them automatically.
351 * @throws SamlException
352 * @throws JsonDebugException
353 * @throws UserRegistrationException
354 * @throws StoppedAuthenticationException
356 public function processLoginCallback(string $samlID, array $samlAttributes): User
358 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
359 $isLoggedIn = auth()->check();
361 if ($this->config['dump_user_details']) {
362 throw new JsonDebugException([
363 'id_from_idp' => $samlID,
364 'attrs_from_idp' => $samlAttributes,
365 'attrs_after_parsing' => $userDetails,
369 if ($userDetails['email'] === null) {
370 throw new SamlException(trans('errors.saml_no_email_address'));
374 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
377 $user = $this->registrationService->findOrRegister(
378 $userDetails['name'],
379 $userDetails['email'],
380 $userDetails['external_id']
383 if ($user === null) {
384 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
387 if ($this->shouldSyncGroups()) {
388 $groups = $this->getUserGroups($samlAttributes);
389 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
392 $this->loginService->login($user, 'saml2');