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;
10 use Illuminate\Support\Str;
11 use OneLogin\Saml2\Auth;
12 use OneLogin\Saml2\Error;
13 use OneLogin\Saml2\IdPMetadataParser;
14 use OneLogin\Saml2\ValidationError;
18 * Handles any app-specific SAML tasks.
20 class Saml2Service extends ExternalAuthService
23 protected $registrationService;
27 * Saml2Service constructor.
29 public function __construct(RegistrationService $registrationService, User $user)
31 $this->config = config('saml2');
32 $this->registrationService = $registrationService;
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
83 * @throws UserRegistrationException
85 public function processAcsResponse(?string $requestId): ?User
87 $toolkit = $this->getToolkit();
88 $toolkit->processResponse($requestId);
89 $errors = $toolkit->getErrors();
91 if (!empty($errors)) {
93 'Invalid ACS Response: '.implode(', ', $errors)
97 if (!$toolkit->isAuthenticated()) {
101 $attrs = $toolkit->getAttributes();
102 $id = $toolkit->getNameId();
104 return $this->processLoginCallback($id, $attrs);
108 * Process a response for the single logout service.
111 public function processSlsResponse(?string $requestId): ?string
113 $toolkit = $this->getToolkit();
114 $redirect = $toolkit->processSLO(true, $requestId, false, null, true);
116 $errors = $toolkit->getErrors();
118 if (!empty($errors)) {
120 'Invalid SLS Response: '.implode(', ', $errors)
124 $this->actionLogout();
129 * Do the required actions to log a user out.
131 protected function actionLogout()
134 session()->invalidate();
138 * Get the metadata for this service provider.
141 public function metadata(): string
143 $toolKit = $this->getToolkit();
144 $settings = $toolKit->getSettings();
145 $metadata = $settings->getSPMetadata();
146 $errors = $settings->validateMetadata($metadata);
148 if (!empty($errors)) {
150 'Invalid SP metadata: '.implode(', ', $errors),
151 Error::METADATA_SP_INVALID
159 * Load the underlying Onelogin SAML2 toolkit.
163 protected function getToolkit(): Auth
165 $settings = $this->config['onelogin'];
166 $overrides = $this->config['onelogin_overrides'] ?? [];
168 if ($overrides && is_string($overrides)) {
169 $overrides = json_decode($overrides, true);
172 $metaDataSettings = [];
173 if ($this->config['autoload_from_metadata']) {
174 $metaDataSettings = IdPMetadataParser::parseRemoteXML($settings['idp']['entityId']);
177 $spSettings = $this->loadOneloginServiceProviderDetails();
178 $settings = array_replace_recursive($settings, $spSettings, $metaDataSettings, $overrides);
179 return new Auth($settings);
183 * Load dynamic service provider options required by the onelogin toolkit.
185 protected function loadOneloginServiceProviderDetails(): array
188 'entityId' => url('/saml2/metadata'),
189 'assertionConsumerService' => [
190 'url' => url('/saml2/acs'),
192 'singleLogoutService' => [
193 'url' => url('/saml2/sls')
198 'baseurl' => url('/saml2'),
204 * Check if groups should be synced.
206 protected function shouldSyncGroups(): bool
208 return $this->config['user_to_groups'] !== false;
212 * Calculate the display name
214 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
216 $displayNameAttr = $this->config['display_name_attributes'];
219 foreach ($displayNameAttr as $dnAttr) {
220 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
221 if ($dnComponent !== null) {
222 $displayName[] = $dnComponent;
226 if (count($displayName) == 0) {
227 $displayName = $defaultValue;
229 $displayName = implode(' ', $displayName);
236 * Get the value to use as the external id saved in BookStack
237 * used to link the user to an existing BookStack DB user.
239 protected function getExternalId(array $samlAttributes, string $defaultValue)
241 $userNameAttr = $this->config['external_id_attribute'];
242 if ($userNameAttr === null) {
243 return $defaultValue;
246 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
250 * Extract the details of a user from a SAML response.
252 protected function getUserDetails(string $samlID, $samlAttributes): array
254 $emailAttr = $this->config['email_attribute'];
255 $externalId = $this->getExternalId($samlAttributes, $samlID);
257 $defaultEmail = filter_var($samlID, FILTER_VALIDATE_EMAIL) ? $samlID : null;
258 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, $defaultEmail);
261 'external_id' => $externalId,
262 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
264 'saml_id' => $samlID,
269 * Get the groups a user is a part of from the SAML response.
271 public function getUserGroups(array $samlAttributes): array
273 $groupsAttr = $this->config['group_attribute'];
274 $userGroups = $samlAttributes[$groupsAttr] ?? null;
276 if (!is_array($userGroups)) {
284 * For an array of strings, return a default for an empty array,
285 * a string for an array with one element and the full array for
286 * more than one element.
288 protected function simplifyValue(array $data, $defaultValue)
290 switch (count($data)) {
292 $data = $defaultValue;
302 * Get a property from an SAML response.
303 * Handles properties potentially being an array.
305 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
307 if (isset($samlAttributes[$propertyKey])) {
308 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
311 return $defaultValue;
315 * Get the user from the database for the specified details.
316 * @throws UserRegistrationException
318 protected function getOrRegisterUser(array $userDetails): ?User
320 $user = $this->user->newQuery()
321 ->where('external_auth_id', '=', $userDetails['external_id'])
324 if (is_null($user)) {
326 'name' => $userDetails['name'],
327 'email' => $userDetails['email'],
328 'password' => Str::random(32),
329 'external_auth_id' => $userDetails['external_id'],
332 $user = $this->registrationService->registerUser($userData, null, false);
339 * Process the SAML response for a user. Login the user when
340 * they exist, optionally registering them automatically.
341 * @throws SamlException
342 * @throws JsonDebugException
343 * @throws UserRegistrationException
345 public function processLoginCallback(string $samlID, array $samlAttributes): User
347 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
348 $isLoggedIn = auth()->check();
350 if ($this->config['dump_user_details']) {
351 throw new JsonDebugException([
352 'id_from_idp' => $samlID,
353 'attrs_from_idp' => $samlAttributes,
354 'attrs_after_parsing' => $userDetails,
358 if ($userDetails['email'] === null) {
359 throw new SamlException(trans('errors.saml_no_email_address'));
363 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
366 $user = $this->getOrRegisterUser($userDetails);
367 if ($user === null) {
368 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
371 if ($this->shouldSyncGroups()) {
372 $groups = $this->getUserGroups($samlAttributes);
373 $this->syncWithGroups($user, $groups);
376 auth()->login($user);
377 Activity::add(ActivityType::AUTH_LOGIN, "saml2; {$user->logDescriptor()}");