1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Auth\User;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
7 use BookStack\Exceptions\UserRegistrationException;
8 use BookStack\Facades\Activity;
9 use BookStack\Facades\Theme;
10 use BookStack\Theming\ThemeEvents;
12 use Illuminate\Support\Str;
13 use OneLogin\Saml2\Auth;
14 use OneLogin\Saml2\Error;
15 use OneLogin\Saml2\IdPMetadataParser;
16 use OneLogin\Saml2\ValidationError;
20 * Handles any app-specific SAML tasks.
22 class Saml2Service extends ExternalAuthService
25 protected $registrationService;
29 * Saml2Service constructor.
31 public function __construct(RegistrationService $registrationService, User $user)
33 $this->config = config('saml2');
34 $this->registrationService = $registrationService;
39 * Initiate a login flow.
42 public function login(): array
44 $toolKit = $this->getToolkit();
45 $returnRoute = url('/saml2/acs');
47 'url' => $toolKit->login($returnRoute, [], false, false, true),
48 'id' => $toolKit->getLastRequestID(),
53 * Initiate a logout flow.
56 public function logout(): array
58 $toolKit = $this->getToolkit();
59 $returnRoute = url('/');
62 $url = $toolKit->logout($returnRoute, [], null, null, true);
63 $id = $toolKit->getLastRequestID();
64 } catch (Error $error) {
65 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
69 $this->actionLogout();
74 return ['url' => $url, 'id' => $id];
78 * Process the ACS response from the idp and return the
79 * matching, or new if registration active, user matched to the idp.
80 * Returns null if not authenticated.
82 * @throws SamlException
83 * @throws ValidationError
84 * @throws JsonDebugException
85 * @throws UserRegistrationException
87 public function processAcsResponse(?string $requestId): ?User
89 $toolkit = $this->getToolkit();
90 $toolkit->processResponse($requestId);
91 $errors = $toolkit->getErrors();
93 if (!empty($errors)) {
95 'Invalid ACS Response: '.implode(', ', $errors)
99 if (!$toolkit->isAuthenticated()) {
103 $attrs = $toolkit->getAttributes();
104 $id = $toolkit->getNameId();
106 return $this->processLoginCallback($id, $attrs);
110 * Process a response for the single logout service.
113 public function processSlsResponse(?string $requestId): ?string
115 $toolkit = $this->getToolkit();
116 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
118 $errors = $toolkit->getErrors();
120 if (!empty($errors)) {
122 'Invalid SLS Response: '.implode(', ', $errors)
126 $this->actionLogout();
131 * Do the required actions to log a user out.
133 protected function actionLogout()
136 session()->invalidate();
140 * Get the metadata for this service provider.
143 public function metadata(): string
145 $toolKit = $this->getToolkit();
146 $settings = $toolKit->getSettings();
147 $metadata = $settings->getSPMetadata();
148 $errors = $settings->validateMetadata($metadata);
150 if (!empty($errors)) {
152 'Invalid SP metadata: '.implode(', ', $errors),
153 Error::METADATA_SP_INVALID
161 * Load the underlying Onelogin SAML2 toolkit.
165 protected function getToolkit(): Auth
167 $settings = $this->config['onelogin'];
168 $overrides = $this->config['onelogin_overrides'] ?? [];
170 if ($overrides && is_string($overrides)) {
171 $overrides = json_decode($overrides, true);
174 $metaDataSettings = [];
175 if ($this->config['autoload_from_metadata']) {
176 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
179 $spSettings = $this->loadOneloginServiceProviderDetails();
180 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
181 return new Auth($settings);
185 * Load dynamic service provider options required by the onelogin toolkit.
187 protected function loadOneloginServiceProviderDetails(): array
190 'entityId' => url('/saml2/metadata'),
191 'assertionConsumerService' => [
192 'url' => url('/saml2/acs'),
194 'singleLogoutService' => [
195 'url' => url('/saml2/sls')
200 'baseurl' => url('/saml2'),
206 * Check if groups should be synced.
208 protected function shouldSyncGroups(): bool
210 return $this->config['user_to_groups'] !== false;
214 * Calculate the display name
216 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
218 $displayNameAttr = $this->config['display_name_attributes'];
221 foreach ($displayNameAttr as $dnAttr) {
222 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
223 if ($dnComponent !== null) {
224 $displayName[] = $dnComponent;
228 if (count($displayName) == 0) {
229 $displayName = $defaultValue;
231 $displayName = implode(' ', $displayName);
238 * Get the value to use as the external id saved in BookStack
239 * used to link the user to an existing BookStack DB user.
241 protected function getExternalId(array $samlAttributes, string $defaultValue)
243 $userNameAttr = $this->config['external_id_attribute'];
244 if ($userNameAttr === null) {
245 return $defaultValue;
248 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
252 * Extract the details of a user from a SAML response.
254 protected function getUserDetails(string $samlID, $samlAttributes): array
256 $emailAttr = $this->config['email_attribute'];
257 $externalId = $this->getExternalId($samlAttributes, $samlID);
259 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
260 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
263 'external_id' => $externalId,
264 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
266 'saml_id' => $samlID,
271 * Get the groups a user is a part of from the SAML response.
273 public function getUserGroups(array $samlAttributes): array
275 $groupsAttr = $this->config['group_attribute'];
276 $userGroups = $samlAttributes[$groupsAttr] ?? null;
278 if (!is_array($userGroups)) {
286 * For an array of strings, return a default for an empty array,
287 * a string for an array with one element and the full array for
288 * more than one element.
290 protected function simplifyValue(array $data, $defaultValue)
292 switch (count($data)) {
294 $data = $defaultValue;
304 * Get a property from an SAML response.
305 * Handles properties potentially being an array.
307 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
309 if (isset($samlAttributes[$propertyKey])) {
310 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
313 return $defaultValue;
317 * Get the user from the database for the specified details.
318 * @throws UserRegistrationException
320 protected function getOrRegisterUser(array $userDetails): ?User
322 $user = $this->user->newQuery()
323 ->where('external_auth_id', '=', $userDetails['external_id'])
326 if (is_null($user)) {
328 'name' => $userDetails['name'],
329 'email' => $userDetails['email'],
330 'password' => Str::random(32),
331 'external_auth_id' => $userDetails['external_id'],
334 $user = $this->registrationService->registerUser($userData, null, false);
341 * Process the SAML response for a user. Login the user when
342 * they exist, optionally registering them automatically.
343 * @throws SamlException
344 * @throws JsonDebugException
345 * @throws UserRegistrationException
347 public function processLoginCallback(string $samlID, array $samlAttributes): User
349 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
350 $isLoggedIn = auth()->check();
352 if ($this->config['dump_user_details']) {
353 throw new JsonDebugException([
354 'id_from_idp' => $samlID,
355 'attrs_from_idp' => $samlAttributes,
356 'attrs_after_parsing' => $userDetails,
360 if ($userDetails['email'] === null) {
361 throw new SamlException(trans('errors.saml_no_email_address'));
365 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
368 $user = $this->getOrRegisterUser($userDetails);
369 if ($user === null) {
370 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
373 if ($this->shouldSyncGroups()) {
374 $groups = $this->getUserGroups($samlAttributes);
375 $this->syncWithGroups($user, $groups);
378 auth()->login($user);
379 Activity::add(ActivityType::AUTH_LOGIN, "saml2; {$user->logDescriptor()}");
380 Theme::dispatch(ThemeEvents::AUTH_LOGIN, 'saml2', $user);