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 $email = auth()->user()['email'];
69 $nameIdFormat = env('SAML2_SP_NAME_ID_Format', null);
70 $nameIdSPNameQualifier = env('SAML2_SP_NAME_ID_SP_NAME_QUALIFIER', null);
72 $url = $toolKit->logout($returnRoute, [], $email, null, true, $nameIdFormat, null, $nameIdSPNameQualifier);
73 $id = $toolKit->getLastRequestID();
74 } catch (Error $error) {
75 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
79 $this->actionLogout();
84 return ['url' => $url, 'id' => $id];
88 * Process the ACS response from the idp and return the
89 * matching, or new if registration active, user matched to the idp.
90 * Returns null if not authenticated.
93 * @throws SamlException
94 * @throws ValidationError
95 * @throws JsonDebugException
96 * @throws UserRegistrationException
98 public function processAcsResponse(string $requestId, string $samlResponse): ?User
100 // The SAML2 toolkit expects the response to be within the $_POST superglobal
101 // so we need to manually put it back there at this point.
102 $_POST['SAMLResponse'] = $samlResponse;
103 $toolkit = $this->getToolkit();
104 $toolkit->processResponse($requestId);
105 $errors = $toolkit->getErrors();
107 if (!empty($errors)) {
109 'Invalid ACS Response: ' . implode(', ', $errors)
113 if (!$toolkit->isAuthenticated()) {
117 $attrs = $toolkit->getAttributes();
118 $id = $toolkit->getNameId();
120 return $this->processLoginCallback($id, $attrs);
124 * Process a response for the single logout service.
128 public function processSlsResponse(?string $requestId): ?string
130 $toolkit = $this->getToolkit();
131 $retrieveParametersFromServer = env('SAML2_RETRIEVE_PARAMETERS_FROM_SERVER', false);
133 $redirect = $toolkit->processSLO(true, $requestId, $retrieveParametersFromServer, null, true);
135 $errors = $toolkit->getErrors();
137 if (!empty($errors)) {
139 'Invalid SLS Response: ' . implode(', ', $errors)
143 $this->actionLogout();
149 * Do the required actions to log a user out.
151 protected function actionLogout()
154 session()->invalidate();
158 * Get the metadata for this service provider.
162 public function metadata(): string
164 $toolKit = $this->getToolkit();
165 $settings = $toolKit->getSettings();
166 $metadata = $settings->getSPMetadata();
167 $errors = $settings->validateMetadata($metadata);
169 if (!empty($errors)) {
171 'Invalid SP metadata: ' . implode(', ', $errors),
172 Error::METADATA_SP_INVALID
180 * Load the underlying Onelogin SAML2 toolkit.
185 protected function getToolkit(): Auth
187 $settings = $this->config['onelogin'];
188 $overrides = $this->config['onelogin_overrides'] ?? [];
190 if ($overrides && is_string($overrides)) {
191 $overrides = json_decode($overrides, true);
194 $metaDataSettings = [];
195 if ($this->config['autoload_from_metadata']) {
196 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
199 $spSettings = $this->loadOneloginServiceProviderDetails();
200 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
202 return new Auth($settings);
206 * Load dynamic service provider options required by the onelogin toolkit.
208 protected function loadOneloginServiceProviderDetails(): array
211 'entityId' => url('/saml2/metadata'),
212 'assertionConsumerService' => [
213 'url' => url('/saml2/acs'),
215 'singleLogoutService' => [
216 'url' => url('/saml2/sls'),
221 'baseurl' => url('/saml2'),
227 * Check if groups should be synced.
229 protected function shouldSyncGroups(): bool
231 return $this->config['user_to_groups'] !== false;
235 * Calculate the display name.
237 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
239 $displayNameAttr = $this->config['display_name_attributes'];
242 foreach ($displayNameAttr as $dnAttr) {
243 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
244 if ($dnComponent !== null) {
245 $displayName[] = $dnComponent;
249 if (count($displayName) == 0) {
250 $displayName = $defaultValue;
252 $displayName = implode(' ', $displayName);
259 * Get the value to use as the external id saved in BookStack
260 * used to link the user to an existing BookStack DB user.
262 protected function getExternalId(array $samlAttributes, string $defaultValue)
264 $userNameAttr = $this->config['external_id_attribute'];
265 if ($userNameAttr === null) {
266 return $defaultValue;
269 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
273 * Extract the details of a user from a SAML response.
275 * @return array{external_id: string, name: string, email: string, saml_id: string}
277 protected function getUserDetails(string $samlID, $samlAttributes): array
279 $emailAttr = $this->config['email_attribute'];
280 $externalId = $this->getExternalId($samlAttributes, $samlID);
282 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
283 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
286 'external_id' => $externalId,
287 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
289 'saml_id' => $samlID,
294 * Get the groups a user is a part of from the SAML response.
296 public function getUserGroups(array $samlAttributes): array
298 $groupsAttr = $this->config['group_attribute'];
299 $userGroups = $samlAttributes[$groupsAttr] ?? null;
301 if (!is_array($userGroups)) {
309 * For an array of strings, return a default for an empty array,
310 * a string for an array with one element and the full array for
311 * more than one element.
313 protected function simplifyValue(array $data, $defaultValue)
315 switch (count($data)) {
317 $data = $defaultValue;
328 * Get a property from an SAML response.
329 * Handles properties potentially being an array.
331 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
333 if (isset($samlAttributes[$propertyKey])) {
334 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
337 return $defaultValue;
341 * Process the SAML response for a user. Login the user when
342 * they exist, optionally registering them automatically.
344 * @throws SamlException
345 * @throws JsonDebugException
346 * @throws UserRegistrationException
347 * @throws StoppedAuthenticationException
349 public function processLoginCallback(string $samlID, array $samlAttributes): User
351 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
352 $isLoggedIn = auth()->check();
354 if ($this->config['dump_user_details']) {
355 throw new JsonDebugException([
356 'id_from_idp' => $samlID,
357 'attrs_from_idp' => $samlAttributes,
358 'attrs_after_parsing' => $userDetails,
362 if ($userDetails['email'] === null) {
363 throw new SamlException(trans('errors.saml_no_email_address'));
367 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
370 $user = $this->registrationService->findOrRegister(
371 $userDetails['name'],
372 $userDetails['email'],
373 $userDetails['external_id']
376 if ($user === null) {
377 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
380 if ($this->shouldSyncGroups()) {
381 $groups = $this->getUserGroups($samlAttributes);
382 $this->groupSyncService->syncUserWithFoundGroups($user, $groups, $this->config['remove_from_groups']);
385 $this->loginService->login($user, 'saml2');