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(
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();
122 return $this->processLoginCallback($id, $attrs);
126 * Process a response for the single logout service.
130 public function processSlsResponse(?string $requestId): ?string
132 $toolkit = $this->getToolkit();
134 // The $retrieveParametersFromServer in the call below will mean the library will take the query
135 // parameters, used for the response signing, from the raw $_SERVER['QUERY_STRING']
136 // value so that the exact encoding format is matched when checking the signature.
137 // This is primarily due to ADFS encoding query params with lowercase percent encoding while
138 // PHP (And most other sensible providers) standardise on uppercase.
139 $redirect = $toolkit->processSLO(true, $requestId, true, null, true);
140 $errors = $toolkit->getErrors();
142 if (!empty($errors)) {
144 'Invalid SLS Response: ' . implode(', ', $errors)
148 $this->actionLogout();
154 * Do the required actions to log a user out.
156 protected function actionLogout()
159 session()->invalidate();
163 * Get the metadata for this service provider.
167 public function metadata(): string
169 $toolKit = $this->getToolkit(true);
170 $settings = $toolKit->getSettings();
171 $metadata = $settings->getSPMetadata();
172 $errors = $settings->validateMetadata($metadata);
174 if (!empty($errors)) {
176 'Invalid SP metadata: ' . implode(', ', $errors),
177 Error::METADATA_SP_INVALID
185 * Load the underlying Onelogin SAML2 toolkit.
190 protected function getToolkit(bool $spOnly = false): Auth
192 $settings = $this->config['onelogin'];
193 $overrides = $this->config['onelogin_overrides'] ?? [];
195 if ($overrides && is_string($overrides)) {
196 $overrides = json_decode($overrides, true);
199 $metaDataSettings = [];
200 if (!$spOnly && $this->config['autoload_from_metadata']) {
201 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
204 $spSettings = $this->loadOneloginServiceProviderDetails();
205 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
207 return new Auth($settings, $spOnly);
211 * Load dynamic service provider options required by the onelogin toolkit.
213 protected function loadOneloginServiceProviderDetails(): array
216 'entityId' => url('/saml2/metadata'),
217 'assertionConsumerService' => [
218 'url' => url('/saml2/acs'),
220 'singleLogoutService' => [
221 'url' => url('/saml2/sls'),
226 'baseurl' => url('/saml2'),
232 * Check if groups should be synced.
234 protected function shouldSyncGroups(): bool
236 return $this->config['user_to_groups'] !== false;
240 * Calculate the display name.
242 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
244 $displayNameAttr = $this->config['display_name_attributes'];
247 foreach ($displayNameAttr as $dnAttr) {
248 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
249 if ($dnComponent !== null) {
250 $displayName[] = $dnComponent;
254 if (count($displayName) == 0) {
255 $displayName = $defaultValue;
257 $displayName = implode(' ', $displayName);
264 * Get the value to use as the external id saved in BookStack
265 * used to link the user to an existing BookStack DB user.
267 protected function getExternalId(array $samlAttributes, string $defaultValue)
269 $userNameAttr = $this->config['external_id_attribute'];
270 if ($userNameAttr === null) {
271 return $defaultValue;
274 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
278 * Extract the details of a user from a SAML response.
280 * @return array{external_id: string, name: string, email: string, saml_id: string}
282 protected function getUserDetails(string $samlID, $samlAttributes): array
284 $emailAttr = $this->config['email_attribute'];
285 $externalId = $this->getExternalId($samlAttributes, $samlID);
287 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
288 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
291 'external_id' => $externalId,
292 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
294 'saml_id' => $samlID,
299 * Get the groups a user is a part of from the SAML response.
301 public function getUserGroups(array $samlAttributes): array
303 $groupsAttr = $this->config['group_attribute'];
304 $userGroups = $samlAttributes[$groupsAttr] ?? null;
306 if (!is_array($userGroups)) {
314 * For an array of strings, return a default for an empty array,
315 * a string for an array with one element and the full array for
316 * more than one element.
318 protected function simplifyValue(array $data, $defaultValue)
320 switch (count($data)) {
322 $data = $defaultValue;
333 * Get a property from an SAML response.
334 * Handles properties potentially being an array.
336 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
338 if (isset($samlAttributes[$propertyKey])) {
339 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
342 return $defaultValue;
346 * Process the SAML response for a user. Login the user when
347 * they exist, optionally registering them automatically.
349 * @throws SamlException
350 * @throws JsonDebugException
351 * @throws UserRegistrationException
352 * @throws StoppedAuthenticationException
354 public function processLoginCallback(string $samlID, array $samlAttributes): User
356 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
357 $isLoggedIn = auth()->check();
359 if ($this->config['dump_user_details']) {
360 throw new JsonDebugException([
361 'id_from_idp' => $samlID,
362 'attrs_from_idp' => $samlAttributes,
363 'attrs_after_parsing' => $userDetails,
367 if ($userDetails['email'] === null) {
368 throw new SamlException(trans('errors.saml_no_email_address'));
372 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
375 $user = $this->registrationService->findOrRegister(
376 $userDetails['name'],
377 $userDetails['email'],
378 $userDetails['external_id']
381 if ($user === null) {
382 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
385 if ($this->shouldSyncGroups()) {
386 $groups = $this->getUserGroups($samlAttributes);
387 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
390 $this->loginService->login($user, 'saml2');