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.
20 class Saml2Service extends ExternalAuthService
23 protected $registrationService;
24 protected $loginService;
27 * Saml2Service constructor.
29 public function __construct(RegistrationService $registrationService, LoginService $loginService, User $user)
31 parent::__construct($registrationService, $user);
33 $this->config = config('saml2');
34 $this->registrationService = $registrationService;
35 $this->loginService = $loginService;
39 * Initiate a login flow.
43 public function login(): array
45 $toolKit = $this->getToolkit();
46 $returnRoute = url('/saml2/acs');
49 'url' => $toolKit->login($returnRoute, [], false, false, true),
50 'id' => $toolKit->getLastRequestID(),
55 * Initiate a logout flow.
59 public function logout(): array
61 $toolKit = $this->getToolkit();
62 $returnRoute = url('/');
65 $url = $toolKit->logout($returnRoute, [], null, null, true);
66 $id = $toolKit->getLastRequestID();
67 } catch (Error $error) {
68 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
72 $this->actionLogout();
77 return ['url' => $url, 'id' => $id];
81 * Process the ACS response from the idp and return the
82 * matching, or new if registration active, user matched to the idp.
83 * Returns null if not authenticated.
86 * @throws SamlException
87 * @throws ValidationError
88 * @throws JsonDebugException
89 * @throws UserRegistrationException
91 public function processAcsResponse(?string $requestId): ?User
93 $toolkit = $this->getToolkit();
94 $toolkit->processResponse($requestId);
95 $errors = $toolkit->getErrors();
97 if (!empty($errors)) {
99 'Invalid ACS Response: ' . implode(', ', $errors)
103 if (!$toolkit->isAuthenticated()) {
107 $attrs = $toolkit->getAttributes();
108 $id = $toolkit->getNameId();
110 return $this->processLoginCallback($id, $attrs);
114 * Process a response for the single logout service.
118 public function processSlsResponse(?string $requestId): ?string
120 $toolkit = $this->getToolkit();
121 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
123 $errors = $toolkit->getErrors();
125 if (!empty($errors)) {
127 'Invalid SLS Response: ' . implode(', ', $errors)
131 $this->actionLogout();
137 * Do the required actions to log a user out.
139 protected function actionLogout()
142 session()->invalidate();
146 * Get the metadata for this service provider.
150 public function metadata(): string
152 $toolKit = $this->getToolkit();
153 $settings = $toolKit->getSettings();
154 $metadata = $settings->getSPMetadata();
155 $errors = $settings->validateMetadata($metadata);
157 if (!empty($errors)) {
159 'Invalid SP metadata: ' . implode(', ', $errors),
160 Error::METADATA_SP_INVALID
168 * Load the underlying Onelogin SAML2 toolkit.
173 protected function getToolkit(): Auth
175 $settings = $this->config['onelogin'];
176 $overrides = $this->config['onelogin_overrides'] ?? [];
178 if ($overrides && is_string($overrides)) {
179 $overrides = json_decode($overrides, true);
182 $metaDataSettings = [];
183 if ($this->config['autoload_from_metadata']) {
184 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
187 $spSettings = $this->loadOneloginServiceProviderDetails();
188 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
190 return new Auth($settings);
194 * Load dynamic service provider options required by the onelogin toolkit.
196 protected function loadOneloginServiceProviderDetails(): array
199 'entityId' => url('/saml2/metadata'),
200 'assertionConsumerService' => [
201 'url' => url('/saml2/acs'),
203 'singleLogoutService' => [
204 'url' => url('/saml2/sls'),
209 'baseurl' => url('/saml2'),
215 * Check if groups should be synced.
217 protected function shouldSyncGroups(): bool
219 return $this->config['user_to_groups'] !== false;
223 * Calculate the display name.
225 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
227 $displayNameAttr = $this->config['display_name_attributes'];
230 foreach ($displayNameAttr as $dnAttr) {
231 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
232 if ($dnComponent !== null) {
233 $displayName[] = $dnComponent;
237 if (count($displayName) == 0) {
238 $displayName = $defaultValue;
240 $displayName = implode(' ', $displayName);
247 * Get the value to use as the external id saved in BookStack
248 * used to link the user to an existing BookStack DB user.
250 protected function getExternalId(array $samlAttributes, string $defaultValue)
252 $userNameAttr = $this->config['external_id_attribute'];
253 if ($userNameAttr === null) {
254 return $defaultValue;
257 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
261 * Extract the details of a user from a SAML response.
263 protected function getUserDetails(string $samlID, $samlAttributes): array
265 $emailAttr = $this->config['email_attribute'];
266 $externalId = $this->getExternalId($samlAttributes, $samlID);
268 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
269 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
272 'external_id' => $externalId,
273 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
275 'saml_id' => $samlID,
280 * Get the groups a user is a part of from the SAML response.
282 public function getUserGroups(array $samlAttributes): array
284 $groupsAttr = $this->config['group_attribute'];
285 $userGroups = $samlAttributes[$groupsAttr] ?? null;
287 if (!is_array($userGroups)) {
295 * For an array of strings, return a default for an empty array,
296 * a string for an array with one element and the full array for
297 * more than one element.
299 protected function simplifyValue(array $data, $defaultValue)
301 switch (count($data)) {
303 $data = $defaultValue;
314 * Get a property from an SAML response.
315 * Handles properties potentially being an array.
317 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
319 if (isset($samlAttributes[$propertyKey])) {
320 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
323 return $defaultValue;
327 * Process the SAML response for a user. Login the user when
328 * they exist, optionally registering them automatically.
330 * @throws SamlException
331 * @throws JsonDebugException
332 * @throws UserRegistrationException
333 * @throws StoppedAuthenticationException
335 public function processLoginCallback(string $samlID, array $samlAttributes): User
337 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
338 $isLoggedIn = auth()->check();
340 if ($this->config['dump_user_details']) {
341 throw new JsonDebugException([
342 'id_from_idp' => $samlID,
343 'attrs_from_idp' => $samlAttributes,
344 'attrs_after_parsing' => $userDetails,
348 if ($userDetails['email'] === null) {
349 throw new SamlException(trans('errors.saml_no_email_address'));
353 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
356 $user = $this->getOrRegisterUser($userDetails);
357 if ($user === null) {
358 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
361 if ($this->shouldSyncGroups()) {
362 $groups = $this->getUserGroups($samlAttributes);
363 $this->syncWithGroups($user, $groups);
366 $this->loginService->login($user, 'saml2');