1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\SamlException;
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
26 * Saml2Service constructor.
28 public function __construct(UserRepo $userRepo, User $user)
30 $this->config = config('saml2');
31 $this->userRepo = $userRepo;
33 $this->enabled = config('saml2.enabled') === true;
37 * Initiate a login flow.
40 public function login(): array
42 $toolKit = $this->getToolkit();
43 $returnRoute = url('/saml2/acs');
45 'url' => $toolKit->login($returnRoute, [], false, false, true),
46 'id' => $toolKit->getLastRequestID(),
51 * Initiate a logout flow.
54 public function logout(): array
56 $toolKit = $this->getToolkit();
57 $returnRoute = url('/');
60 $url = $toolKit->logout($returnRoute, [], null, null, true);
61 $id = $toolKit->getLastRequestID();
62 } catch (Error $error) {
63 if ($error->getCode() !== Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED) {
67 $this->actionLogout();
72 return ['url' => $url, 'id' => $id];
76 * Process the ACS response from the idp and return the
77 * matching, or new if registration active, user matched to the idp.
78 * Returns null if not authenticated.
80 * @throws SamlException
81 * @throws ValidationError
82 * @throws JsonDebugException
84 public function processAcsResponse(?string $requestId): ?User
86 $toolkit = $this->getToolkit();
87 $toolkit->processResponse($requestId);
88 $errors = $toolkit->getErrors();
90 if (!empty($errors)) {
92 'Invalid ACS Response: '.implode(', ', $errors)
96 if (!$toolkit->isAuthenticated()) {
100 $attrs = $toolkit->getAttributes();
101 $id = $toolkit->getNameId();
103 return $this->processLoginCallback($id, $attrs);
107 * Process a response for the single logout service.
110 public function processSlsResponse(?string $requestId): ?string
112 $toolkit = $this->getToolkit();
113 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
115 $errors = $toolkit->getErrors();
117 if (!empty($errors)) {
119 'Invalid SLS Response: '.implode(', ', $errors)
123 $this->actionLogout();
128 * Do the required actions to log a user out.
130 protected function actionLogout()
133 session()->invalidate();
137 * Get the metadata for this service provider.
140 public function metadata(): string
142 $toolKit = $this->getToolkit();
143 $settings = $toolKit->getSettings();
144 $metadata = $settings->getSPMetadata();
145 $errors = $settings->validateMetadata($metadata);
147 if (!empty($errors)) {
149 'Invalid SP metadata: '.implode(', ', $errors),
150 Error::METADATA_SP_INVALID
158 * Load the underlying Onelogin SAML2 toolkit.
162 protected function getToolkit(): Auth
164 $settings = $this->config['onelogin'];
165 $overrides = $this->config['onelogin_overrides'] ?? [];
167 if ($overrides && is_string($overrides)) {
168 $overrides = json_decode($overrides, true);
171 $metaDataSettings = [];
172 if ($this->config['autoload_from_metadata']) {
173 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
176 $spSettings = $this->loadOneloginServiceProviderDetails();
177 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
178 return new Auth($settings);
182 * Load dynamic service provider options required by the onelogin toolkit.
184 protected function loadOneloginServiceProviderDetails(): array
187 'entityId' => url('/saml2/metadata'),
188 'assertionConsumerService' => [
189 'url' => url('/saml2/acs'),
191 'singleLogoutService' => [
192 'url' => url('/saml2/sls')
197 'baseurl' => url('/saml2'),
203 * Check if groups should be synced.
205 protected function shouldSyncGroups(): bool
207 return $this->enabled && $this->config['user_to_groups'] !== false;
211 * Calculate the display name
213 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
215 $displayNameAttr = $this->config['display_name_attributes'];
218 foreach ($displayNameAttr as $dnAttr) {
219 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
220 if ($dnComponent !== null) {
221 $displayName[] = $dnComponent;
225 if (count($displayName) == 0) {
226 $displayName = $defaultValue;
228 $displayName = implode(' ', $displayName);
235 * Get the value to use as the external id saved in BookStack
236 * used to link the user to an existing BookStack DB user.
238 protected function getExternalId(array $samlAttributes, string $defaultValue)
240 $userNameAttr = $this->config['external_id_attribute'];
241 if ($userNameAttr === null) {
242 return $defaultValue;
245 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
249 * Extract the details of a user from a SAML response.
251 public function getUserDetails(string $samlID, $samlAttributes): array
253 $emailAttr = $this->config['email_attribute'];
254 $externalId = $this->getExternalId($samlAttributes, $samlID);
256 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
257 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
260 'external_id' => $externalId,
261 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
263 'saml_id' => $samlID,
268 * Get the groups a user is a part of from the SAML response.
270 public function getUserGroups(array $samlAttributes): array
272 $groupsAttr = $this->config['group_attribute'];
273 $userGroups = $samlAttributes[$groupsAttr] ?? null;
275 if (!is_array($userGroups)) {
283 * For an array of strings, return a default for an empty array,
284 * a string for an array with one element and the full array for
285 * more than one element.
287 protected function simplifyValue(array $data, $defaultValue)
289 switch (count($data)) {
291 $data = $defaultValue;
301 * Get a property from an SAML response.
302 * Handles properties potentially being an array.
304 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
306 if (isset($samlAttributes[$propertyKey])) {
307 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
310 return $defaultValue;
314 * Register a user that is authenticated but not already registered.
316 protected function registerUser(array $userDetails): User
318 // Create an array of the user data to create a new user instance
320 'name' => $userDetails['name'],
321 'email' => $userDetails['email'],
322 'password' => Str::random(32),
323 'external_auth_id' => $userDetails['external_id'],
324 'email_confirmed' => true,
327 $existingUser = $this->user->newQuery()->where('email', '=', $userDetails['email'])->first();
329 throw new SamlException(trans('errors.saml_email_exists', ['email' => $userDetails['email']]));
332 $user = $this->user->forceCreate($userData);
333 $this->userRepo->attachDefaultRole($user);
334 $this->userRepo->downloadAndAssignUserAvatar($user);
339 * Get the user from the database for the specified details.
341 protected function getOrRegisterUser(array $userDetails): ?User
343 $isRegisterEnabled = $this->config['auto_register'] === true;
345 ->where('external_auth_id', $userDetails['external_id'])
348 if ($user === null && $isRegisterEnabled) {
349 $user = $this->registerUser($userDetails);
356 * Process the SAML response for a user. Login the user when
357 * they exist, optionally registering them automatically.
358 * @throws SamlException
359 * @throws JsonDebugException
361 public function processLoginCallback(string $samlID, array $samlAttributes): User
363 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
364 $isLoggedIn = auth()->check();
366 if ($this->config['dump_user_details']) {
367 throw new JsonDebugException([
368 'id_from_idp' => $samlID,
369 'attrs_from_idp' => $samlAttributes,
370 'attrs_after_parsing' => $userDetails,
374 if ($userDetails['email'] === null) {
375 throw new SamlException(trans('errors.saml_no_email_address'));
379 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
382 $user = $this->getOrRegisterUser($userDetails);
383 if ($user === null) {
384 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
387 if ($this->shouldSyncGroups()) {
388 $groups = $this->getUserGroups($samlAttributes);
389 $this->syncWithGroups($user, $groups);
392 auth()->login($user);