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 OneLogin\Saml2\Auth;
9 use OneLogin\Saml2\Error;
10 use OneLogin\Saml2\IdPMetadataParser;
11 use OneLogin\Saml2\ValidationError;
15 * Handles any app-specific SAML tasks.
17 class Saml2Service extends ExternalAuthService
22 * Saml2Service constructor.
24 public function __construct(RegistrationService $registrationService, User $user)
26 parent::__construct($registrationService, $user);
28 $this->config = config('saml2');
32 * Initiate a login flow.
35 public function login(): array
37 $toolKit = $this->getToolkit();
38 $returnRoute = url('/saml2/acs');
40 'url' => $toolKit->login($returnRoute, [], false, false, true),
41 'id' => $toolKit->getLastRequestID(),
46 * Initiate a logout flow.
49 public function logout(): array
51 $toolKit = $this->getToolkit();
52 $returnRoute = url('/');
55 $url = $toolKit->logout($returnRoute, [], null, null, true);
56 $id = $toolKit->getLastRequestID();
57 } catch (Error $error) {
58 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
62 $this->actionLogout();
67 return ['url' => $url, 'id' => $id];
71 * Process the ACS response from the idp and return the
72 * matching, or new if registration active, user matched to the idp.
73 * Returns null if not authenticated.
75 * @throws SamlException
76 * @throws ValidationError
77 * @throws JsonDebugException
78 * @throws UserRegistrationException
80 public function processAcsResponse(?string $requestId): ?User
82 $toolkit = $this->getToolkit();
83 $toolkit->processResponse($requestId);
84 $errors = $toolkit->getErrors();
86 if (!empty($errors)) {
88 'Invalid ACS Response: '.implode(', ', $errors)
92 if (!$toolkit->isAuthenticated()) {
96 $attrs = $toolkit->getAttributes();
97 $id = $toolkit->getNameId();
99 return $this->processLoginCallback($id, $attrs);
103 * Process a response for the single logout service.
106 public function processSlsResponse(?string $requestId): ?string
108 $toolkit = $this->getToolkit();
109 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
111 $errors = $toolkit->getErrors();
113 if (!empty($errors)) {
115 'Invalid SLS Response: '.implode(', ', $errors)
119 $this->actionLogout();
124 * Do the required actions to log a user out.
126 protected function actionLogout()
129 session()->invalidate();
133 * Get the metadata for this service provider.
136 public function metadata(): string
138 $toolKit = $this->getToolkit();
139 $settings = $toolKit->getSettings();
140 $metadata = $settings->getSPMetadata();
141 $errors = $settings->validateMetadata($metadata);
143 if (!empty($errors)) {
145 'Invalid SP metadata: '.implode(', ', $errors),
146 Error::METADATA_SP_INVALID
154 * Load the underlying Onelogin SAML2 toolkit.
158 protected function getToolkit(): Auth
160 $settings = $this->config['onelogin'];
161 $overrides = $this->config['onelogin_overrides'] ?? [];
163 if ($overrides && is_string($overrides)) {
164 $overrides = json_decode($overrides, true);
167 $metaDataSettings = [];
168 if ($this->config['autoload_from_metadata']) {
169 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
172 $spSettings = $this->loadOneloginServiceProviderDetails();
173 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
174 return new Auth($settings);
178 * Load dynamic service provider options required by the onelogin toolkit.
180 protected function loadOneloginServiceProviderDetails(): array
183 'entityId' => url('/saml2/metadata'),
184 'assertionConsumerService' => [
185 'url' => url('/saml2/acs'),
187 'singleLogoutService' => [
188 'url' => url('/saml2/sls')
193 'baseurl' => url('/saml2'),
199 * Check if groups should be synced.
201 protected function shouldSyncGroups(): bool
203 return $this->config['user_to_groups'] !== false;
207 * Calculate the display name
209 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
211 $displayNameAttr = $this->config['display_name_attributes'];
214 foreach ($displayNameAttr as $dnAttr) {
215 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
216 if ($dnComponent !== null) {
217 $displayName[] = $dnComponent;
221 if (count($displayName) == 0) {
222 $displayName = $defaultValue;
224 $displayName = implode(' ', $displayName);
231 * Get the value to use as the external id saved in BookStack
232 * used to link the user to an existing BookStack DB user.
234 protected function getExternalId(array $samlAttributes, string $defaultValue)
236 $userNameAttr = $this->config['external_id_attribute'];
237 if ($userNameAttr === null) {
238 return $defaultValue;
241 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
245 * Extract the details of a user from a SAML response.
247 protected function getUserDetails(string $samlID, $samlAttributes): array
249 $emailAttr = $this->config['email_attribute'];
250 $externalId = $this->getExternalId($samlAttributes, $samlID);
252 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
253 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
256 'external_id' => $externalId,
257 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
259 'saml_id' => $samlID,
264 * Get the groups a user is a part of from the SAML response.
266 public function getUserGroups(array $samlAttributes): array
268 $groupsAttr = $this->config['group_attribute'];
269 $userGroups = $samlAttributes[$groupsAttr] ?? null;
271 if (!is_array($userGroups)) {
279 * For an array of strings, return a default for an empty array,
280 * a string for an array with one element and the full array for
281 * more than one element.
283 protected function simplifyValue(array $data, $defaultValue)
285 switch (count($data)) {
287 $data = $defaultValue;
297 * Get a property from an SAML response.
298 * Handles properties potentially being an array.
300 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
302 if (isset($samlAttributes[$propertyKey])) {
303 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
306 return $defaultValue;
310 * Process the SAML response for a user. Login the user when
311 * they exist, optionally registering them automatically.
312 * @throws SamlException
313 * @throws JsonDebugException
314 * @throws UserRegistrationException
316 public function processLoginCallback(string $samlID, array $samlAttributes): User
318 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
319 $isLoggedIn = auth()->check();
321 if ($this->config['dump_user_details']) {
322 throw new JsonDebugException([
323 'id_from_idp' => $samlID,
324 'attrs_from_idp' => $samlAttributes,
325 'attrs_after_parsing' => $userDetails,
329 if ($userDetails['email'] === null) {
330 throw new SamlException(trans('errors.saml_no_email_address'));
334 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
337 $user = $this->getOrRegisterUser($userDetails);
338 if ($user === null) {
339 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
342 if ($this->shouldSyncGroups()) {
343 $groups = $this->getUserGroups($samlAttributes);
344 $this->syncWithGroups($user, $groups);
347 auth()->login($user);