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\UserRegistrationException;
10 use BookStack\Facades\Activity;
11 use BookStack\Facades\Theme;
12 use BookStack\Theming\ThemeEvents;
14 use Illuminate\Support\Str;
15 use OneLogin\Saml2\Auth;
16 use OneLogin\Saml2\Error;
17 use OneLogin\Saml2\IdPMetadataParser;
18 use OneLogin\Saml2\ValidationError;
22 * Handles any app-specific SAML tasks.
24 class Saml2Service extends ExternalAuthService
27 protected $registrationService;
31 * Saml2Service constructor.
33 public function __construct(RegistrationService $registrationService, User $user)
35 $this->config = config('saml2');
36 $this->registrationService = $registrationService;
41 * Initiate a login flow.
45 public function login(): array
47 $toolKit = $this->getToolkit();
48 $returnRoute = url('/saml2/acs');
51 'url' => $toolKit->login($returnRoute, [], false, false, true),
52 'id' => $toolKit->getLastRequestID(),
57 * Initiate a logout flow.
61 public function logout(): array
63 $toolKit = $this->getToolkit();
64 $returnRoute = url('/');
67 $url = $toolKit->logout($returnRoute, [], null, null, true);
68 $id = $toolKit->getLastRequestID();
69 } catch (Error $error) {
70 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
74 $this->actionLogout();
79 return ['url' => $url, 'id' => $id];
83 * Process the ACS response from the idp and return the
84 * matching, or new if registration active, user matched to the idp.
85 * Returns null if not authenticated.
88 * @throws SamlException
89 * @throws ValidationError
90 * @throws JsonDebugException
91 * @throws UserRegistrationException
93 public function processAcsResponse(?string $requestId): ?User
95 $toolkit = $this->getToolkit();
96 $toolkit->processResponse($requestId);
97 $errors = $toolkit->getErrors();
99 if (!empty($errors)) {
101 'Invalid ACS Response: ' . implode(', ', $errors)
105 if (!$toolkit->isAuthenticated()) {
109 $attrs = $toolkit->getAttributes();
110 $id = $toolkit->getNameId();
112 return $this->processLoginCallback($id, $attrs);
116 * Process a response for the single logout service.
120 public function processSlsResponse(?string $requestId): ?string
122 $toolkit = $this->getToolkit();
123 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
125 $errors = $toolkit->getErrors();
127 if (!empty($errors)) {
129 'Invalid SLS Response: ' . implode(', ', $errors)
133 $this->actionLogout();
139 * Do the required actions to log a user out.
141 protected function actionLogout()
144 session()->invalidate();
148 * Get the metadata for this service provider.
152 public function metadata(): string
154 $toolKit = $this->getToolkit();
155 $settings = $toolKit->getSettings();
156 $metadata = $settings->getSPMetadata();
157 $errors = $settings->validateMetadata($metadata);
159 if (!empty($errors)) {
161 'Invalid SP metadata: ' . implode(', ', $errors),
162 Error::METADATA_SP_INVALID
170 * Load the underlying Onelogin SAML2 toolkit.
175 protected function getToolkit(): Auth
177 $settings = $this->config['onelogin'];
178 $overrides = $this->config['onelogin_overrides'] ?? [];
180 if ($overrides && is_string($overrides)) {
181 $overrides = json_decode($overrides, true);
184 $metaDataSettings = [];
185 if ($this->config['autoload_from_metadata']) {
186 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
189 $spSettings = $this->loadOneloginServiceProviderDetails();
190 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
192 return new Auth($settings);
196 * Load dynamic service provider options required by the onelogin toolkit.
198 protected function loadOneloginServiceProviderDetails(): array
201 'entityId' => url('/saml2/metadata'),
202 'assertionConsumerService' => [
203 'url' => url('/saml2/acs'),
205 'singleLogoutService' => [
206 'url' => url('/saml2/sls'),
211 'baseurl' => url('/saml2'),
217 * Check if groups should be synced.
219 protected function shouldSyncGroups(): bool
221 return $this->config['user_to_groups'] !== false;
225 * Calculate the display name.
227 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
229 $displayNameAttr = $this->config['display_name_attributes'];
232 foreach ($displayNameAttr as $dnAttr) {
233 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
234 if ($dnComponent !== null) {
235 $displayName[] = $dnComponent;
239 if (count($displayName) == 0) {
240 $displayName = $defaultValue;
242 $displayName = implode(' ', $displayName);
249 * Get the value to use as the external id saved in BookStack
250 * used to link the user to an existing BookStack DB user.
252 protected function getExternalId(array $samlAttributes, string $defaultValue)
254 $userNameAttr = $this->config['external_id_attribute'];
255 if ($userNameAttr === null) {
256 return $defaultValue;
259 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
263 * Extract the details of a user from a SAML response.
265 protected function getUserDetails(string $samlID, $samlAttributes): array
267 $emailAttr = $this->config['email_attribute'];
268 $externalId = $this->getExternalId($samlAttributes, $samlID);
270 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
271 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
274 'external_id' => $externalId,
275 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
277 'saml_id' => $samlID,
282 * Get the groups a user is a part of from the SAML response.
284 public function getUserGroups(array $samlAttributes): array
286 $groupsAttr = $this->config['group_attribute'];
287 $userGroups = $samlAttributes[$groupsAttr] ?? null;
289 if (!is_array($userGroups)) {
297 * For an array of strings, return a default for an empty array,
298 * a string for an array with one element and the full array for
299 * more than one element.
301 protected function simplifyValue(array $data, $defaultValue)
303 switch (count($data)) {
305 $data = $defaultValue;
316 * Get a property from an SAML response.
317 * Handles properties potentially being an array.
319 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
321 if (isset($samlAttributes[$propertyKey])) {
322 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
325 return $defaultValue;
329 * Get the user from the database for the specified details.
331 * @throws UserRegistrationException
333 protected function getOrRegisterUser(array $userDetails): ?User
335 $user = $this->user->newQuery()
336 ->where('external_auth_id', '=', $userDetails['external_id'])
339 if (is_null($user)) {
341 'name' => $userDetails['name'],
342 'email' => $userDetails['email'],
343 'password' => Str::random(32),
344 'external_auth_id' => $userDetails['external_id'],
347 $user = $this->registrationService->registerUser($userData, null, false);
354 * Process the SAML response for a user. Login the user when
355 * they exist, optionally registering them automatically.
357 * @throws SamlException
358 * @throws JsonDebugException
359 * @throws UserRegistrationException
361 public function processLoginCallback(string $samlID, array $samlAttributes): User
363 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
364 $isLoggedIn = auth()->check();
366 if ($this->config['dump_user_details']) {
367 throw new JsonDebugException([
368 'id_from_idp' => $samlID,
369 'attrs_from_idp' => $samlAttributes,
370 'attrs_after_parsing' => $userDetails,
374 if ($userDetails['email'] === null) {
375 throw new SamlException(trans('errors.saml_no_email_address'));
379 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
382 $user = $this->getOrRegisterUser($userDetails);
383 if ($user === null) {
384 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
387 if ($this->shouldSyncGroups()) {
388 $groups = $this->getUserGroups($samlAttributes);
389 $this->syncWithGroups($user, $groups);
392 auth()->login($user);
393 Activity::add(ActivityType::AUTH_LOGIN, "saml2; {$user->logDescriptor()}");
394 Theme::dispatch(ThemeEvents::AUTH_LOGIN, 'saml2', $user);