1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\SamlException;
6 use BookStack\Exceptions\UserRegistrationException;
8 use Illuminate\Support\Str;
9 use OneLogin\Saml2\Auth;
10 use OneLogin\Saml2\Error;
11 use OneLogin\Saml2\IdPMetadataParser;
12 use OneLogin\Saml2\ValidationError;
16 * Handles any app-specific SAML tasks.
18 class Saml2Service extends ExternalAuthService
21 protected $registrationService;
25 * Saml2Service constructor.
27 public function __construct(RegistrationService $registrationService, User $user)
29 $this->config = config('saml2');
30 $this->registrationService = $registrationService;
35 * Initiate a login flow.
38 public function login(): array
40 $toolKit = $this->getToolkit();
41 $returnRoute = url('/saml2/acs');
43 'url' => $toolKit->login($returnRoute, [], false, false, true),
44 'id' => $toolKit->getLastRequestID(),
49 * Initiate a logout flow.
52 public function logout(): array
54 $toolKit = $this->getToolkit();
55 $returnRoute = url('/');
58 $url = $toolKit->logout($returnRoute, [], null, null, true);
59 $id = $toolKit->getLastRequestID();
60 } catch (Error $error) {
61 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
65 $this->actionLogout();
70 return ['url' => $url, 'id' => $id];
74 * Process the ACS response from the idp and return the
75 * matching, or new if registration active, user matched to the idp.
76 * Returns null if not authenticated.
78 * @throws SamlException
79 * @throws ValidationError
80 * @throws JsonDebugException
81 * @throws UserRegistrationException
83 public function processAcsResponse(?string $requestId): ?User
85 $toolkit = $this->getToolkit();
86 $toolkit->processResponse($requestId);
87 $errors = $toolkit->getErrors();
89 if (!empty($errors)) {
91 'Invalid ACS Response: '.implode(', ', $errors)
95 if (!$toolkit->isAuthenticated()) {
99 $attrs = $toolkit->getAttributes();
100 $id = $toolkit->getNameId();
102 return $this->processLoginCallback($id, $attrs);
106 * Process a response for the single logout service.
109 public function processSlsResponse(?string $requestId): ?string
111 $toolkit = $this->getToolkit();
112 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
114 $errors = $toolkit->getErrors();
116 if (!empty($errors)) {
118 'Invalid SLS Response: '.implode(', ', $errors)
122 $this->actionLogout();
127 * Do the required actions to log a user out.
129 protected function actionLogout()
132 session()->invalidate();
136 * Get the metadata for this service provider.
139 public function metadata(): string
141 $toolKit = $this->getToolkit();
142 $settings = $toolKit->getSettings();
143 $metadata = $settings->getSPMetadata();
144 $errors = $settings->validateMetadata($metadata);
146 if (!empty($errors)) {
148 'Invalid SP metadata: '.implode(', ', $errors),
149 Error::METADATA_SP_INVALID
157 * Load the underlying Onelogin SAML2 toolkit.
161 protected function getToolkit(): Auth
163 $settings = $this->config['onelogin'];
164 $overrides = $this->config['onelogin_overrides'] ?? [];
166 if ($overrides && is_string($overrides)) {
167 $overrides = json_decode($overrides, true);
170 $metaDataSettings = [];
171 if ($this->config['autoload_from_metadata']) {
172 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
175 $spSettings = $this->loadOneloginServiceProviderDetails();
176 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
177 return new Auth($settings);
181 * Load dynamic service provider options required by the onelogin toolkit.
183 protected function loadOneloginServiceProviderDetails(): array
186 'entityId' => url('/saml2/metadata'),
187 'assertionConsumerService' => [
188 'url' => url('/saml2/acs'),
190 'singleLogoutService' => [
191 'url' => url('/saml2/sls')
196 'baseurl' => url('/saml2'),
202 * Check if groups should be synced.
204 protected function shouldSyncGroups(): bool
206 return $this->config['user_to_groups'] !== false;
210 * Calculate the display name
212 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
214 $displayNameAttr = $this->config['display_name_attributes'];
217 foreach ($displayNameAttr as $dnAttr) {
218 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
219 if ($dnComponent !== null) {
220 $displayName[] = $dnComponent;
224 if (count($displayName) == 0) {
225 $displayName = $defaultValue;
227 $displayName = implode(' ', $displayName);
234 * Get the value to use as the external id saved in BookStack
235 * used to link the user to an existing BookStack DB user.
237 protected function getExternalId(array $samlAttributes, string $defaultValue)
239 $userNameAttr = $this->config['external_id_attribute'];
240 if ($userNameAttr === null) {
241 return $defaultValue;
244 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
248 * Extract the details of a user from a SAML response.
250 protected function getUserDetails(string $samlID, $samlAttributes): array
252 $emailAttr = $this->config['email_attribute'];
253 $externalId = $this->getExternalId($samlAttributes, $samlID);
255 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
256 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
259 'external_id' => $externalId,
260 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
262 'saml_id' => $samlID,
267 * Get the groups a user is a part of from the SAML response.
269 public function getUserGroups(array $samlAttributes): array
271 $groupsAttr = $this->config['group_attribute'];
272 $userGroups = $samlAttributes[$groupsAttr] ?? null;
274 if (!is_array($userGroups)) {
282 * For an array of strings, return a default for an empty array,
283 * a string for an array with one element and the full array for
284 * more than one element.
286 protected function simplifyValue(array $data, $defaultValue)
288 switch (count($data)) {
290 $data = $defaultValue;
300 * Get a property from an SAML response.
301 * Handles properties potentially being an array.
303 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
305 if (isset($samlAttributes[$propertyKey])) {
306 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
309 return $defaultValue;
313 * Get the user from the database for the specified details.
314 * @throws SamlException
315 * @throws UserRegistrationException
317 protected function getOrRegisterUser(array $userDetails): ?User
319 $user = $this->user->newQuery()
320 ->where('external_auth_id', '=', $userDetails['external_id'])
323 if (is_null($user)) {
325 'name' => $userDetails['name'],
326 'email' => $userDetails['email'],
327 'password' => Str::random(32),
328 'external_auth_id' => $userDetails['external_id'],
331 $user = $this->registrationService->registerUser($userData, null, false);
338 * Process the SAML response for a user. Login the user when
339 * they exist, optionally registering them automatically.
340 * @throws SamlException
341 * @throws JsonDebugException
342 * @throws UserRegistrationException
344 public function processLoginCallback(string $samlID, array $samlAttributes): User
346 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
347 $isLoggedIn = auth()->check();
349 if ($this->config['dump_user_details']) {
350 throw new JsonDebugException([
351 'id_from_idp' => $samlID,
352 'attrs_from_idp' => $samlAttributes,
353 'attrs_after_parsing' => $userDetails,
357 if ($userDetails['email'] === null) {
358 throw new SamlException(trans('errors.saml_no_email_address'));
362 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
365 $user = $this->getOrRegisterUser($userDetails);
366 if ($user === null) {
367 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
370 if ($this->shouldSyncGroups()) {
371 $groups = $this->getUserGroups($samlAttributes);
372 $this->syncWithGroups($user, $groups);
375 auth()->login($user);