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
35 $this->config = config('saml2');
36 $this->registrationService = $registrationService;
37 $this->loginService = $loginService;
38 $this->groupSyncService = $groupSyncService;
42 * Initiate a login flow.
46 public function login(): array
48 $toolKit = $this->getToolkit();
49 $returnRoute = url('/saml2/acs');
52 'url' => $toolKit->login($returnRoute, [], false, false, true),
53 'id' => $toolKit->getLastRequestID(),
58 * Initiate a logout flow.
62 public function logout(): array
64 $toolKit = $this->getToolkit();
65 $returnRoute = url('/');
68 $url = $toolKit->logout($returnRoute, [], null, null, true);
69 $id = $toolKit->getLastRequestID();
70 } catch (Error $error) {
71 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
75 $this->actionLogout();
80 return ['url' => $url, 'id' => $id];
84 * Process the ACS response from the idp and return the
85 * matching, or new if registration active, user matched to the idp.
86 * Returns null if not authenticated.
89 * @throws SamlException
90 * @throws ValidationError
91 * @throws JsonDebugException
92 * @throws UserRegistrationException
94 public function processAcsResponse(string $requestId, string $samlResponse): ?User
96 // The SAML2 toolkit expects the response to be within the $_POST superglobal
97 // so we need to manually put it back there at this point.
98 $_POST['SAMLResponse'] = $samlResponse;
99 $toolkit = $this->getToolkit();
100 $toolkit->processResponse($requestId);
101 $errors = $toolkit->getErrors();
103 if (!empty($errors)) {
105 'Invalid ACS Response: ' . implode(', ', $errors)
109 if (!$toolkit->isAuthenticated()) {
113 $attrs = $toolkit->getAttributes();
114 $id = $toolkit->getNameId();
116 return $this->processLoginCallback($id, $attrs);
120 * Process a response for the single logout service.
124 public function processSlsResponse(?string $requestId): ?string
126 $toolkit = $this->getToolkit();
127 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
129 $errors = $toolkit->getErrors();
131 if (!empty($errors)) {
133 'Invalid SLS Response: ' . implode(', ', $errors)
137 $this->actionLogout();
143 * Do the required actions to log a user out.
145 protected function actionLogout()
148 session()->invalidate();
152 * Get the metadata for this service provider.
156 public function metadata(): string
158 $toolKit = $this->getToolkit();
159 $settings = $toolKit->getSettings();
160 $metadata = $settings->getSPMetadata();
161 $errors = $settings->validateMetadata($metadata);
163 if (!empty($errors)) {
165 'Invalid SP metadata: ' . implode(', ', $errors),
166 Error::METADATA_SP_INVALID
174 * Load the underlying Onelogin SAML2 toolkit.
179 protected function getToolkit(): Auth
181 $settings = $this->config['onelogin'];
182 $overrides = $this->config['onelogin_overrides'] ?? [];
184 if ($overrides && is_string($overrides)) {
185 $overrides = json_decode($overrides, true);
188 $metaDataSettings = [];
189 if ($this->config['autoload_from_metadata']) {
190 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
193 $spSettings = $this->loadOneloginServiceProviderDetails();
194 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
196 return new Auth($settings);
200 * Load dynamic service provider options required by the onelogin toolkit.
202 protected function loadOneloginServiceProviderDetails(): array
205 'entityId' => url('/saml2/metadata'),
206 'assertionConsumerService' => [
207 'url' => url('/saml2/acs'),
209 'singleLogoutService' => [
210 'url' => url('/saml2/sls'),
215 'baseurl' => url('/saml2'),
221 * Check if groups should be synced.
223 protected function shouldSyncGroups(): bool
225 return $this->config['user_to_groups'] !== false;
229 * Calculate the display name.
231 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
233 $displayNameAttr = $this->config['display_name_attributes'];
236 foreach ($displayNameAttr as $dnAttr) {
237 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
238 if ($dnComponent !== null) {
239 $displayName[] = $dnComponent;
243 if (count($displayName) == 0) {
244 $displayName = $defaultValue;
246 $displayName = implode(' ', $displayName);
253 * Get the value to use as the external id saved in BookStack
254 * used to link the user to an existing BookStack DB user.
256 protected function getExternalId(array $samlAttributes, string $defaultValue)
258 $userNameAttr = $this->config['external_id_attribute'];
259 if ($userNameAttr === null) {
260 return $defaultValue;
263 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
267 * Extract the details of a user from a SAML response.
269 * @return array{external_id: string, name: string, email: string, saml_id: string}
271 protected function getUserDetails(string $samlID, $samlAttributes): array
273 $emailAttr = $this->config['email_attribute'];
274 $externalId = $this->getExternalId($samlAttributes, $samlID);
276 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
277 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
280 'external_id' => $externalId,
281 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
283 'saml_id' => $samlID,
288 * Get the groups a user is a part of from the SAML response.
290 public function getUserGroups(array $samlAttributes): array
292 $groupsAttr = $this->config['group_attribute'];
293 $userGroups = $samlAttributes[$groupsAttr] ?? null;
295 if (!is_array($userGroups)) {
303 * For an array of strings, return a default for an empty array,
304 * a string for an array with one element and the full array for
305 * more than one element.
307 protected function simplifyValue(array $data, $defaultValue)
309 switch (count($data)) {
311 $data = $defaultValue;
322 * Get a property from an SAML response.
323 * Handles properties potentially being an array.
325 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
327 if (isset($samlAttributes[$propertyKey])) {
328 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
331 return $defaultValue;
335 * Process the SAML response for a user. Login the user when
336 * they exist, optionally registering them automatically.
338 * @throws SamlException
339 * @throws JsonDebugException
340 * @throws UserRegistrationException
341 * @throws StoppedAuthenticationException
343 public function processLoginCallback(string $samlID, array $samlAttributes): User
345 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
346 $isLoggedIn = auth()->check();
348 if ($this->config['dump_user_details']) {
349 throw new JsonDebugException([
350 'id_from_idp' => $samlID,
351 'attrs_from_idp' => $samlAttributes,
352 'attrs_after_parsing' => $userDetails,
356 if ($userDetails['email'] === null) {
357 throw new SamlException(trans('errors.saml_no_email_address'));
361 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
364 $user = $this->registrationService->findOrRegister(
365 $userDetails['name'],
366 $userDetails['email'],
367 $userDetails['external_id']
370 if ($user === null) {
371 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
374 if ($this->shouldSyncGroups()) {
375 $groups = $this->getUserGroups($samlAttributes);
376 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
379 $this->loginService->login($user, 'saml2');