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\Error;
13 use OneLogin\Saml2\IdPMetadataParser;
14 use OneLogin\Saml2\ValidationError;
18 * Handles any app-specific SAML tasks.
23 protected $registrationService;
24 protected $loginService;
25 protected $groupSyncService;
28 * Saml2Service constructor.
30 public function __construct(
31 RegistrationService $registrationService,
32 LoginService $loginService,
33 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(): array
65 $toolKit = $this->getToolkit();
66 $returnRoute = url('/');
69 $url = $toolKit->logout($returnRoute, [], null, null, true);
70 $id = $toolKit->getLastRequestID();
71 } catch (Error $error) {
72 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
76 $this->actionLogout();
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): ?User
97 $toolkit = $this->getToolkit();
98 $toolkit->processResponse($requestId);
99 $errors = $toolkit->getErrors();
101 if (!empty($errors)) {
103 'Invalid ACS Response: ' . implode(', ', $errors)
107 if (!$toolkit->isAuthenticated()) {
111 $attrs = $toolkit->getAttributes();
112 $id = $toolkit->getNameId();
114 return $this->processLoginCallback($id, $attrs);
118 * Process a response for the single logout service.
122 public function processSlsResponse(?string $requestId): ?string
124 $toolkit = $this->getToolkit();
125 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
127 $errors = $toolkit->getErrors();
129 if (!empty($errors)) {
131 'Invalid SLS Response: ' . implode(', ', $errors)
135 $this->actionLogout();
141 * Do the required actions to log a user out.
143 protected function actionLogout()
146 session()->invalidate();
150 * Get the metadata for this service provider.
154 public function metadata(): string
156 $toolKit = $this->getToolkit();
157 $settings = $toolKit->getSettings();
158 $metadata = $settings->getSPMetadata();
159 $errors = $settings->validateMetadata($metadata);
161 if (!empty($errors)) {
163 'Invalid SP metadata: ' . implode(', ', $errors),
164 Error::METADATA_SP_INVALID
172 * Load the underlying Onelogin SAML2 toolkit.
177 protected function getToolkit(): Auth
179 $settings = $this->config['onelogin'];
180 $overrides = $this->config['onelogin_overrides'] ?? [];
182 if ($overrides && is_string($overrides)) {
183 $overrides = json_decode($overrides, true);
186 $metaDataSettings = [];
187 if ($this->config['autoload_from_metadata']) {
188 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
191 $spSettings = $this->loadOneloginServiceProviderDetails();
192 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
194 return new Auth($settings);
198 * Load dynamic service provider options required by the onelogin toolkit.
200 protected function loadOneloginServiceProviderDetails(): array
203 'entityId' => url('/saml2/metadata'),
204 'assertionConsumerService' => [
205 'url' => url('/saml2/acs'),
207 'singleLogoutService' => [
208 'url' => url('/saml2/sls'),
213 'baseurl' => url('/saml2'),
219 * Check if groups should be synced.
221 protected function shouldSyncGroups(): bool
223 return $this->config['user_to_groups'] !== false;
227 * Calculate the display name.
229 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
231 $displayNameAttr = $this->config['display_name_attributes'];
234 foreach ($displayNameAttr as $dnAttr) {
235 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
236 if ($dnComponent !== null) {
237 $displayName[] = $dnComponent;
241 if (count($displayName) == 0) {
242 $displayName = $defaultValue;
244 $displayName = implode(' ', $displayName);
251 * Get the value to use as the external id saved in BookStack
252 * used to link the user to an existing BookStack DB user.
254 protected function getExternalId(array $samlAttributes, string $defaultValue)
256 $userNameAttr = $this->config['external_id_attribute'];
257 if ($userNameAttr === null) {
258 return $defaultValue;
261 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
265 * Extract the details of a user from a SAML response.
266 * @return array{external_id: string, name: string, email: string, saml_id: string}
268 protected function getUserDetails(string $samlID, $samlAttributes): array
270 $emailAttr = $this->config['email_attribute'];
271 $externalId = $this->getExternalId($samlAttributes, $samlID);
273 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
274 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
277 'external_id' => $externalId,
278 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
280 'saml_id' => $samlID,
285 * Get the groups a user is a part of from the SAML response.
287 public function getUserGroups(array $samlAttributes): array
289 $groupsAttr = $this->config['group_attribute'];
290 $userGroups = $samlAttributes[$groupsAttr] ?? null;
292 if (!is_array($userGroups)) {
300 * For an array of strings, return a default for an empty array,
301 * a string for an array with one element and the full array for
302 * more than one element.
304 protected function simplifyValue(array $data, $defaultValue)
306 switch (count($data)) {
308 $data = $defaultValue;
319 * Get a property from an SAML response.
320 * Handles properties potentially being an array.
322 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
324 if (isset($samlAttributes[$propertyKey])) {
325 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
328 return $defaultValue;
332 * Process the SAML response for a user. Login the user when
333 * they exist, optionally registering them automatically.
335 * @throws SamlException
336 * @throws JsonDebugException
337 * @throws UserRegistrationException
338 * @throws StoppedAuthenticationException
340 public function processLoginCallback(string $samlID, array $samlAttributes): User
342 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
343 $isLoggedIn = auth()->check();
345 if ($this->config['dump_user_details']) {
346 throw new JsonDebugException([
347 'id_from_idp' => $samlID,
348 'attrs_from_idp' => $samlAttributes,
349 'attrs_after_parsing' => $userDetails,
353 if ($userDetails['email'] === null) {
354 throw new SamlException(trans('errors.saml_no_email_address'));
358 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
361 $user = $this->registrationService->findOrRegister(
362 $userDetails['name'], $userDetails['email'], $userDetails['external_id']
365 if ($user === null) {
366 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
369 if ($this->shouldSyncGroups()) {
370 $groups = $this->getUserGroups($samlAttributes);
371 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
374 $this->loginService->login($user, 'saml2');