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)) {
112 $reason = $toolkit->getLastErrorReason();
113 $message = 'Invalid ACS Response; Errors: ' . implode(', ', $errors);
114 $message .= $reason ? "; Reason: {$reason}" : '';
115 throw new Error($message);
118 if (!$toolkit->isAuthenticated()) {
122 $attrs = $toolkit->getAttributes();
123 $id = $toolkit->getNameId();
125 return $this->processLoginCallback($id, $attrs);
129 * Process a response for the single logout service.
133 public function processSlsResponse(?string $requestId): ?string
135 $toolkit = $this->getToolkit();
137 // The $retrieveParametersFromServer in the call below will mean the library will take the query
138 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
139 // value so that the exact encoding format is matched when checking the signature.
140 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
141 // PHP (And most other sensible providers) standardise on uppercase.
142 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
143 $errors = $toolkit->getErrors();
145 if (!empty($errors)) {
147 'Invalid SLS Response: ' . implode(', ', $errors)
151 $this->actionLogout();
157 * Do the required actions to log a user out.
159 protected function actionLogout()
162 session()->invalidate();
166 * Get the metadata for this service provider.
170 public function metadata(): string
172 $toolKit = $this->getToolkit();
173 $settings = $toolKit->getSettings();
174 $metadata = $settings->getSPMetadata();
175 $errors = $settings->validateMetadata($metadata);
177 if (!empty($errors)) {
179 'Invalid SP metadata: ' . implode(', ', $errors),
180 Error::METADATA_SP_INVALID
188 * Load the underlying Onelogin SAML2 toolkit.
193 protected function getToolkit(): Auth
195 $settings = $this->config['onelogin'];
196 $overrides = $this->config['onelogin_overrides'] ?? [];
198 if ($overrides && is_string($overrides)) {
199 $overrides = json_decode($overrides, true);
202 $metaDataSettings = [];
203 if ($this->config['autoload_from_metadata']) {
204 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
207 $spSettings = $this->loadOneloginServiceProviderDetails();
208 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
210 return new Auth($settings);
214 * Load dynamic service provider options required by the onelogin toolkit.
216 protected function loadOneloginServiceProviderDetails(): array
219 'entityId' => url('/saml2/metadata'),
220 'assertionConsumerService' => [
221 'url' => url('/saml2/acs'),
223 'singleLogoutService' => [
224 'url' => url('/saml2/sls'),
229 'baseurl' => url('/saml2'),
235 * Check if groups should be synced.
237 protected function shouldSyncGroups(): bool
239 return $this->config['user_to_groups'] !== false;
243 * Calculate the display name.
245 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
247 $displayNameAttr = $this->config['display_name_attributes'];
250 foreach ($displayNameAttr as $dnAttr) {
251 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
252 if ($dnComponent !== null) {
253 $displayName[] = $dnComponent;
257 if (count($displayName) == 0) {
258 $displayName = $defaultValue;
260 $displayName = implode(' ', $displayName);
267 * Get the value to use as the external id saved in BookStack
268 * used to link the user to an existing BookStack DB user.
270 protected function getExternalId(array $samlAttributes, string $defaultValue)
272 $userNameAttr = $this->config['external_id_attribute'];
273 if ($userNameAttr === null) {
274 return $defaultValue;
277 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
281 * Extract the details of a user from a SAML response.
283 * @return array{external_id: string, name: string, email: string, saml_id: string}
285 protected function getUserDetails(string $samlID, $samlAttributes): array
287 $emailAttr = $this->config['email_attribute'];
288 $externalId = $this->getExternalId($samlAttributes, $samlID);
290 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
291 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
294 'external_id' => $externalId,
295 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
297 'saml_id' => $samlID,
302 * Get the groups a user is a part of from the SAML response.
304 public function getUserGroups(array $samlAttributes): array
306 $groupsAttr = $this->config['group_attribute'];
307 $userGroups = $samlAttributes[$groupsAttr] ?? null;
309 if (!is_array($userGroups)) {
317 * For an array of strings, return a default for an empty array,
318 * a string for an array with one element and the full array for
319 * more than one element.
321 protected function simplifyValue(array $data, $defaultValue)
323 switch (count($data)) {
325 $data = $defaultValue;
336 * Get a property from an SAML response.
337 * Handles properties potentially being an array.
339 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
341 if (isset($samlAttributes[$propertyKey])) {
342 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
345 return $defaultValue;
349 * Process the SAML response for a user. Login the user when
350 * they exist, optionally registering them automatically.
352 * @throws SamlException
353 * @throws JsonDebugException
354 * @throws UserRegistrationException
355 * @throws StoppedAuthenticationException
357 public function processLoginCallback(string $samlID, array $samlAttributes): User
359 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
360 $isLoggedIn = auth()->check();
362 if ($this->config['dump_user_details']) {
363 throw new JsonDebugException([
364 'id_from_idp' => $samlID,
365 'attrs_from_idp' => $samlAttributes,
366 'attrs_after_parsing' => $userDetails,
370 if ($userDetails['email'] === null) {
371 throw new SamlException(trans('errors.saml_no_email_address'));
375 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
378 $user = $this->registrationService->findOrRegister(
379 $userDetails['name'],
380 $userDetails['email'],
381 $userDetails['external_id']
384 if ($user === null) {
385 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
388 if ($this->shouldSyncGroups()) {
389 $groups = $this->getUserGroups($samlAttributes);
390 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
393 $this->loginService->login($user, 'saml2');