3 namespace BookStack\Auth\Access;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Auth\User;
7 use BookStack\Exceptions\JsonDebugException;
8 use BookStack\Exceptions\SamlException;
9 use BookStack\Exceptions\StoppedAuthenticationException;
10 use BookStack\Exceptions\UserRegistrationException;
11 use BookStack\Facades\Activity;
12 use BookStack\Facades\Theme;
13 use BookStack\Theming\ThemeEvents;
15 use Illuminate\Support\Str;
16 use OneLogin\Saml2\Auth;
17 use OneLogin\Saml2\Error;
18 use OneLogin\Saml2\IdPMetadataParser;
19 use OneLogin\Saml2\ValidationError;
23 * Handles any app-specific SAML tasks.
25 class Saml2Service extends ExternalAuthService
28 protected $registrationService;
29 protected $loginService;
32 * Saml2Service constructor.
34 public function __construct(RegistrationService $registrationService, LoginService $loginService)
36 $this->config = config('saml2');
37 $this->registrationService = $registrationService;
38 $this->loginService = $loginService;
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): ?User
96 $toolkit = $this->getToolkit();
97 $toolkit->processResponse($requestId);
98 $errors = $toolkit->getErrors();
100 if (!empty($errors)) {
102 'Invalid ACS Response: ' . implode(', ', $errors)
106 if (!$toolkit->isAuthenticated()) {
110 $attrs = $toolkit->getAttributes();
111 $id = $toolkit->getNameId();
113 return $this->processLoginCallback($id, $attrs);
117 * Process a response for the single logout service.
121 public function processSlsResponse(?string $requestId): ?string
123 $toolkit = $this->getToolkit();
124 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
126 $errors = $toolkit->getErrors();
128 if (!empty($errors)) {
130 'Invalid SLS Response: ' . implode(', ', $errors)
134 $this->actionLogout();
140 * Do the required actions to log a user out.
142 protected function actionLogout()
145 session()->invalidate();
149 * Get the metadata for this service provider.
153 public function metadata(): string
155 $toolKit = $this->getToolkit();
156 $settings = $toolKit->getSettings();
157 $metadata = $settings->getSPMetadata();
158 $errors = $settings->validateMetadata($metadata);
160 if (!empty($errors)) {
162 'Invalid SP metadata: ' . implode(', ', $errors),
163 Error::METADATA_SP_INVALID
171 * Load the underlying Onelogin SAML2 toolkit.
176 protected function getToolkit(): Auth
178 $settings = $this->config['onelogin'];
179 $overrides = $this->config['onelogin_overrides'] ?? [];
181 if ($overrides && is_string($overrides)) {
182 $overrides = json_decode($overrides, true);
185 $metaDataSettings = [];
186 if ($this->config['autoload_from_metadata']) {
187 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
190 $spSettings = $this->loadOneloginServiceProviderDetails();
191 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
193 return new Auth($settings);
197 * Load dynamic service provider options required by the onelogin toolkit.
199 protected function loadOneloginServiceProviderDetails(): array
202 'entityId' => url('/saml2/metadata'),
203 'assertionConsumerService' => [
204 'url' => url('/saml2/acs'),
206 'singleLogoutService' => [
207 'url' => url('/saml2/sls'),
212 'baseurl' => url('/saml2'),
218 * Check if groups should be synced.
220 protected function shouldSyncGroups(): bool
222 return $this->config['user_to_groups'] !== false;
226 * Calculate the display name.
228 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
230 $displayNameAttr = $this->config['display_name_attributes'];
233 foreach ($displayNameAttr as $dnAttr) {
234 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
235 if ($dnComponent !== null) {
236 $displayName[] = $dnComponent;
240 if (count($displayName) == 0) {
241 $displayName = $defaultValue;
243 $displayName = implode(' ', $displayName);
250 * Get the value to use as the external id saved in BookStack
251 * used to link the user to an existing BookStack DB user.
253 protected function getExternalId(array $samlAttributes, string $defaultValue)
255 $userNameAttr = $this->config['external_id_attribute'];
256 if ($userNameAttr === null) {
257 return $defaultValue;
260 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
264 * Extract the details of a user from a SAML response.
266 protected function getUserDetails(string $samlID, $samlAttributes): array
268 $emailAttr = $this->config['email_attribute'];
269 $externalId = $this->getExternalId($samlAttributes, $samlID);
271 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
272 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
275 'external_id' => $externalId,
276 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
278 'saml_id' => $samlID,
283 * Get the groups a user is a part of from the SAML response.
285 public function getUserGroups(array $samlAttributes): array
287 $groupsAttr = $this->config['group_attribute'];
288 $userGroups = $samlAttributes[$groupsAttr] ?? null;
290 if (!is_array($userGroups)) {
298 * For an array of strings, return a default for an empty array,
299 * a string for an array with one element and the full array for
300 * more than one element.
302 protected function simplifyValue(array $data, $defaultValue)
304 switch (count($data)) {
306 $data = $defaultValue;
317 * Get a property from an SAML response.
318 * Handles properties potentially being an array.
320 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
322 if (isset($samlAttributes[$propertyKey])) {
323 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
326 return $defaultValue;
330 * Get the user from the database for the specified details.
332 * @throws UserRegistrationException
334 protected function getOrRegisterUser(array $userDetails): ?User
336 $user = User::query()
337 ->where('external_auth_id', '=', $userDetails['external_id'])
340 if (is_null($user)) {
342 'name' => $userDetails['name'],
343 'email' => $userDetails['email'],
344 'password' => Str::random(32),
345 'external_auth_id' => $userDetails['external_id'],
348 $user = $this->registrationService->registerUser($userData, null, false);
355 * Process the SAML response for a user. Login the user when
356 * they exist, optionally registering them automatically.
358 * @throws SamlException
359 * @throws JsonDebugException
360 * @throws UserRegistrationException
361 * @throws StoppedAuthenticationException
363 public function processLoginCallback(string $samlID, array $samlAttributes): User
365 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
366 $isLoggedIn = auth()->check();
368 if ($this->config['dump_user_details']) {
369 throw new JsonDebugException([
370 'id_from_idp' => $samlID,
371 'attrs_from_idp' => $samlAttributes,
372 'attrs_after_parsing' => $userDetails,
376 if ($userDetails['email'] === null) {
377 throw new SamlException(trans('errors.saml_no_email_address'));
381 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
384 $user = $this->getOrRegisterUser($userDetails);
385 if ($user === null) {
386 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
389 if ($this->shouldSyncGroups()) {
390 $groups = $this->getUserGroups($samlAttributes);
391 $this->syncWithGroups($user, $groups);
394 $this->loginService->login($user, 'saml2');