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 Illuminate\Support\Str;
12 use OneLogin\Saml2\Auth;
13 use OneLogin\Saml2\Error;
14 use OneLogin\Saml2\IdPMetadataParser;
15 use OneLogin\Saml2\ValidationError;
19 * Handles any app-specific SAML tasks.
21 class Saml2Service extends ExternalAuthService
24 protected $registrationService;
25 protected $loginService;
28 * Saml2Service constructor.
30 public function __construct(RegistrationService $registrationService, LoginService $loginService)
32 $this->config = config('saml2');
33 $this->registrationService = $registrationService;
34 $this->loginService = $loginService;
38 * Initiate a login flow.
42 public function login(): array
44 $toolKit = $this->getToolkit();
45 $returnRoute = url('/saml2/acs');
48 'url' => $toolKit->login($returnRoute, [], false, false, true),
49 'id' => $toolKit->getLastRequestID(),
54 * Initiate a logout flow.
58 public function logout(): array
60 $toolKit = $this->getToolkit();
61 $returnRoute = url('/');
64 $url = $toolKit->logout($returnRoute, [], null, null, true);
65 $id = $toolKit->getLastRequestID();
66 } catch (Error $error) {
67 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
71 $this->actionLogout();
76 return ['url' => $url, 'id' => $id];
80 * Process the ACS response from the idp and return the
81 * matching, or new if registration active, user matched to the idp.
82 * Returns null if not authenticated.
85 * @throws SamlException
86 * @throws ValidationError
87 * @throws JsonDebugException
88 * @throws UserRegistrationException
90 public function processAcsResponse(?string $requestId): ?User
92 $toolkit = $this->getToolkit();
93 $toolkit->processResponse($requestId);
94 $errors = $toolkit->getErrors();
96 if (!empty($errors)) {
98 'Invalid ACS Response: ' . implode(', ', $errors)
102 if (!$toolkit->isAuthenticated()) {
106 $attrs = $toolkit->getAttributes();
107 $id = $toolkit->getNameId();
109 return $this->processLoginCallback($id, $attrs);
113 * Process a response for the single logout service.
117 public function processSlsResponse(?string $requestId): ?string
119 $toolkit = $this->getToolkit();
120 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
122 $errors = $toolkit->getErrors();
124 if (!empty($errors)) {
126 'Invalid SLS Response: ' . implode(', ', $errors)
130 $this->actionLogout();
136 * Do the required actions to log a user out.
138 protected function actionLogout()
141 session()->invalidate();
145 * Get the metadata for this service provider.
149 public function metadata(): string
151 $toolKit = $this->getToolkit();
152 $settings = $toolKit->getSettings();
153 $metadata = $settings->getSPMetadata();
154 $errors = $settings->validateMetadata($metadata);
156 if (!empty($errors)) {
158 'Invalid SP metadata: ' . implode(', ', $errors),
159 Error::METADATA_SP_INVALID
167 * Load the underlying Onelogin SAML2 toolkit.
172 protected function getToolkit(): Auth
174 $settings = $this->config['onelogin'];
175 $overrides = $this->config['onelogin_overrides'] ?? [];
177 if ($overrides && is_string($overrides)) {
178 $overrides = json_decode($overrides, true);
181 $metaDataSettings = [];
182 if ($this->config['autoload_from_metadata']) {
183 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
186 $spSettings = $this->loadOneloginServiceProviderDetails();
187 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
189 return new Auth($settings);
193 * Load dynamic service provider options required by the onelogin toolkit.
195 protected function loadOneloginServiceProviderDetails(): array
198 'entityId' => url('/saml2/metadata'),
199 'assertionConsumerService' => [
200 'url' => url('/saml2/acs'),
202 'singleLogoutService' => [
203 'url' => url('/saml2/sls'),
208 'baseurl' => url('/saml2'),
214 * Check if groups should be synced.
216 protected function shouldSyncGroups(): bool
218 return $this->config['user_to_groups'] !== false;
222 * Calculate the display name.
224 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
226 $displayNameAttr = $this->config['display_name_attributes'];
229 foreach ($displayNameAttr as $dnAttr) {
230 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
231 if ($dnComponent !== null) {
232 $displayName[] = $dnComponent;
236 if (count($displayName) == 0) {
237 $displayName = $defaultValue;
239 $displayName = implode(' ', $displayName);
246 * Get the value to use as the external id saved in BookStack
247 * used to link the user to an existing BookStack DB user.
249 protected function getExternalId(array $samlAttributes, string $defaultValue)
251 $userNameAttr = $this->config['external_id_attribute'];
252 if ($userNameAttr === null) {
253 return $defaultValue;
256 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
260 * Extract the details of a user from a SAML response.
262 protected function getUserDetails(string $samlID, $samlAttributes): array
264 $emailAttr = $this->config['email_attribute'];
265 $externalId = $this->getExternalId($samlAttributes, $samlID);
267 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
268 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
271 'external_id' => $externalId,
272 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
274 'saml_id' => $samlID,
279 * Get the groups a user is a part of from the SAML response.
281 public function getUserGroups(array $samlAttributes): array
283 $groupsAttr = $this->config['group_attribute'];
284 $userGroups = $samlAttributes[$groupsAttr] ?? null;
286 if (!is_array($userGroups)) {
294 * For an array of strings, return a default for an empty array,
295 * a string for an array with one element and the full array for
296 * more than one element.
298 protected function simplifyValue(array $data, $defaultValue)
300 switch (count($data)) {
302 $data = $defaultValue;
313 * Get a property from an SAML response.
314 * Handles properties potentially being an array.
316 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
318 if (isset($samlAttributes[$propertyKey])) {
319 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
322 return $defaultValue;
326 * Get the user from the database for the specified details.
328 * @throws UserRegistrationException
330 protected function getOrRegisterUser(array $userDetails): ?User
332 $user = User::query()
333 ->where('external_auth_id', '=', $userDetails['external_id'])
336 if (is_null($user)) {
338 'name' => $userDetails['name'],
339 'email' => $userDetails['email'],
340 'password' => Str::random(32),
341 'external_auth_id' => $userDetails['external_id'],
344 $user = $this->registrationService->registerUser($userData, null, false);
351 * Process the SAML response for a user. Login the user when
352 * they exist, optionally registering them automatically.
354 * @throws SamlException
355 * @throws JsonDebugException
356 * @throws UserRegistrationException
357 * @throws StoppedAuthenticationException
359 public function processLoginCallback(string $samlID, array $samlAttributes): User
361 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
362 $isLoggedIn = auth()->check();
364 if ($this->config['dump_user_details']) {
365 throw new JsonDebugException([
366 'id_from_idp' => $samlID,
367 'attrs_from_idp' => $samlAttributes,
368 'attrs_after_parsing' => $userDetails,
372 if ($userDetails['email'] === null) {
373 throw new SamlException(trans('errors.saml_no_email_address'));
377 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
380 $user = $this->getOrRegisterUser($userDetails);
381 if ($user === null) {
382 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
385 if ($this->shouldSyncGroups()) {
386 $groups = $this->getUserGroups($samlAttributes);
387 $this->syncWithGroups($user, $groups);
390 $this->loginService->login($user, 'saml2');