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 $email = auth()->user()['email'];
65 $nameIdFormat = env('SAML2_SP_NAME_ID_Format', null);
66 $nameIdSPNameQualifier = env('SAML2_SP_NAME_ID_SP_NAME_QUALIFIER', null);
68 $url = $toolKit->logout($returnRoute, [], $email, null, true, $nameIdFormat, null, $nameIdSPNameQualifier);
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 $retrieveParametersFromServer = env('SAML2_RETRIEVE_PARAMETERS_FROM_SERVER', false);
126 $redirect = $toolkit->processSLO(true, $requestId, $retrieveParametersFromServer, null, true);
128 $errors = $toolkit->getErrors();
130 if (!empty($errors)) {
132 'Invalid SLS Response: ' . implode(', ', $errors)
136 $this->actionLogout();
142 * Do the required actions to log a user out.
144 protected function actionLogout()
147 session()->invalidate();
151 * Get the metadata for this service provider.
155 public function metadata(): string
157 $toolKit = $this->getToolkit();
158 $settings = $toolKit->getSettings();
159 $metadata = $settings->getSPMetadata();
160 $errors = $settings->validateMetadata($metadata);
162 if (!empty($errors)) {
164 'Invalid SP metadata: ' . implode(', ', $errors),
165 Error::METADATA_SP_INVALID
173 * Load the underlying Onelogin SAML2 toolkit.
178 protected function getToolkit(): Auth
180 $settings = $this->config['onelogin'];
181 $overrides = $this->config['onelogin_overrides'] ?? [];
183 if ($overrides && is_string($overrides)) {
184 $overrides = json_decode($overrides, true);
187 $metaDataSettings = [];
188 if ($this->config['autoload_from_metadata']) {
189 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
192 $spSettings = $this->loadOneloginServiceProviderDetails();
193 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
195 return new Auth($settings);
199 * Load dynamic service provider options required by the onelogin toolkit.
201 protected function loadOneloginServiceProviderDetails(): array
204 'entityId' => url('/saml2/metadata'),
205 'assertionConsumerService' => [
206 'url' => url('/saml2/acs'),
208 'singleLogoutService' => [
209 'url' => url('/saml2/sls'),
214 'baseurl' => url('/saml2'),
220 * Check if groups should be synced.
222 protected function shouldSyncGroups(): bool
224 return $this->config['user_to_groups'] !== false;
228 * Calculate the display name.
230 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
232 $displayNameAttr = $this->config['display_name_attributes'];
235 foreach ($displayNameAttr as $dnAttr) {
236 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
237 if ($dnComponent !== null) {
238 $displayName[] = $dnComponent;
242 if (count($displayName) == 0) {
243 $displayName = $defaultValue;
245 $displayName = implode(' ', $displayName);
252 * Get the value to use as the external id saved in BookStack
253 * used to link the user to an existing BookStack DB user.
255 protected function getExternalId(array $samlAttributes, string $defaultValue)
257 $userNameAttr = $this->config['external_id_attribute'];
258 if ($userNameAttr === null) {
259 return $defaultValue;
262 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
266 * Extract the details of a user from a SAML response.
268 protected function getUserDetails(string $samlID, $samlAttributes): array
270 $emailAttr = $this->config['email_attribute'];
271 $externalId = $this->getExternalId($samlAttributes, $samlID);
273 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
274 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
277 'external_id' => $externalId,
278 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
280 'saml_id' => $samlID,
285 * Get the groups a user is a part of from the SAML response.
287 public function getUserGroups(array $samlAttributes): array
289 $groupsAttr = $this->config['group_attribute'];
290 $userGroups = $samlAttributes[$groupsAttr] ?? null;
292 if (!is_array($userGroups)) {
300 * For an array of strings, return a default for an empty array,
301 * a string for an array with one element and the full array for
302 * more than one element.
304 protected function simplifyValue(array $data, $defaultValue)
306 switch (count($data)) {
308 $data = $defaultValue;
319 * Get a property from an SAML response.
320 * Handles properties potentially being an array.
322 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
324 if (isset($samlAttributes[$propertyKey])) {
325 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
328 return $defaultValue;
332 * Get the user from the database for the specified details.
334 * @throws UserRegistrationException
336 protected function getOrRegisterUser(array $userDetails): ?User
338 $user = User::query()
339 ->where('external_auth_id', '=', $userDetails['external_id'])
342 if (is_null($user)) {
344 'name' => $userDetails['name'],
345 'email' => $userDetails['email'],
346 'password' => Str::random(32),
347 'external_auth_id' => $userDetails['external_id'],
350 $user = $this->registrationService->registerUser($userData, null, false);
357 * Process the SAML response for a user. Login the user when
358 * they exist, optionally registering them automatically.
360 * @throws SamlException
361 * @throws JsonDebugException
362 * @throws UserRegistrationException
363 * @throws StoppedAuthenticationException
365 public function processLoginCallback(string $samlID, array $samlAttributes): User
367 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
368 $isLoggedIn = auth()->check();
370 if ($this->config['dump_user_details']) {
371 throw new JsonDebugException([
372 'id_from_idp' => $samlID,
373 'attrs_from_idp' => $samlAttributes,
374 'attrs_after_parsing' => $userDetails,
378 if ($userDetails['email'] === null) {
379 throw new SamlException(trans('errors.saml_no_email_address'));
383 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
386 $user = $this->getOrRegisterUser($userDetails);
387 if ($user === null) {
388 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
391 if ($this->shouldSyncGroups()) {
392 $groups = $this->getUserGroups($samlAttributes);
393 $this->syncWithGroups($user, $groups);
396 $this->loginService->login($user, 'saml2');