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;
7 use Illuminate\Support\Str;
8 use OneLogin\Saml2\Auth;
9 use OneLogin\Saml2\Error;
13 * Handles any app-specific SAML tasks.
15 class Saml2Service extends ExternalAuthService
23 * Saml2Service constructor.
25 public function __construct(UserRepo $userRepo, User $user)
27 $this->config = config('saml2');
28 $this->userRepo = $userRepo;
30 $this->enabled = config('saml2.enabled') === true;
34 * Initiate a login flow.
35 * @throws \OneLogin\Saml2\Error
37 public function login(): array
39 $toolKit = $this->getToolkit();
40 $returnRoute = url('/saml2/acs');
42 'url' => $toolKit->login($returnRoute, [], false, false, true),
43 'id' => $toolKit->getLastRequestID(),
48 * Process the ACS response from the idp and return the
49 * matching, or new if registration active, user matched to the idp.
50 * Returns null if not authenticated.
52 * @throws SamlException
53 * @throws \OneLogin\Saml2\ValidationError
54 * @throws JsonDebugException
56 public function processAcsResponse(?string $requestId): ?User
58 $toolkit = $this->getToolkit();
59 $toolkit->processResponse($requestId);
60 $errors = $toolkit->getErrors();
62 if (is_null($requestId)) {
63 throw new SamlException(trans('errors.saml_invalid_response_id'));
66 if (!empty($errors)) {
68 'Invalid ACS Response: '.implode(', ', $errors)
72 if (!$toolkit->isAuthenticated()) {
76 $attrs = $toolkit->getAttributes();
77 $id = $toolkit->getNameId();
79 return $this->processLoginCallback($id, $attrs);
83 * Get the metadata for this service provider.
86 public function metadata(): string
88 $toolKit = $this->getToolkit();
89 $settings = $toolKit->getSettings();
90 $metadata = $settings->getSPMetadata();
91 $errors = $settings->validateMetadata($metadata);
93 if (!empty($errors)) {
95 'Invalid SP metadata: '.implode(', ', $errors),
96 Error::METADATA_SP_INVALID
104 * Load the underlying Onelogin SAML2 toolkit.
105 * @throws \OneLogin\Saml2\Error
107 protected function getToolkit(): Auth
109 $settings = $this->config['onelogin'];
110 $overrides = $this->config['onelogin_overrides'] ?? [];
112 if ($overrides && is_string($overrides)) {
113 $overrides = json_decode($overrides, true);
116 $spSettings = $this->loadOneloginServiceProviderDetails();
117 $settings = array_replace_recursive($settings, $spSettings, $overrides);
118 return new Auth($settings);
122 * Load dynamic service provider options required by the onelogin toolkit.
124 protected function loadOneloginServiceProviderDetails(): array
127 'entityId' => url('/saml2/metadata'),
128 'assertionConsumerService' => [
129 'url' => url('/saml2/acs'),
131 'singleLogoutService' => [
132 'url' => url('/saml2/sls')
137 'baseurl' => url('/saml2'),
143 * Check if groups should be synced.
145 protected function shouldSyncGroups(): bool
147 return $this->enabled && $this->config['user_to_groups'] !== false;
151 * Calculate the display name
153 protected function getUserDisplayName(array $samlAttributes, string $defaultValue): string
155 $displayNameAttr = $this->config['display_name_attributes'];
158 foreach ($displayNameAttr as $dnAttr) {
159 $dnComponent = $this->getSamlResponseAttribute($samlAttributes, $dnAttr, null);
160 if ($dnComponent !== null) {
161 $displayName[] = $dnComponent;
165 if (count($displayName) == 0) {
166 $displayName = $defaultValue;
168 $displayName = implode(' ', $displayName);
175 * Get the value to use as the external id saved in BookStack
176 * used to link the user to an existing BookStack DB user.
178 protected function getExternalId(array $samlAttributes, string $defaultValue)
180 $userNameAttr = $this->config['external_id_attribute'];
181 if ($userNameAttr === null) {
182 return $defaultValue;
185 return $this->getSamlResponseAttribute($samlAttributes, $userNameAttr, $defaultValue);
189 * Extract the details of a user from a SAML response.
190 * @throws SamlException
192 public function getUserDetails(string $samlID, $samlAttributes): array
194 $emailAttr = $this->config['email_attribute'];
195 $externalId = $this->getExternalId($samlAttributes, $samlID);
196 $email = $this->getSamlResponseAttribute($samlAttributes, $emailAttr, null);
198 if ($email === null) {
199 throw new SamlException(trans('errors.saml_no_email_address'));
203 'external_id' => $externalId,
204 'name' => $this->getUserDisplayName($samlAttributes, $externalId),
206 'saml_id' => $samlID,
211 * Get the groups a user is a part of from the SAML response.
213 public function getUserGroups(array $samlAttributes): array
215 $groupsAttr = $this->config['group_attribute'];
216 $userGroups = $samlAttributes[$groupsAttr] ?? null;
218 if (!is_array($userGroups)) {
226 * For an array of strings, return a default for an empty array,
227 * a string for an array with one element and the full array for
228 * more than one element.
230 protected function simplifyValue(array $data, $defaultValue)
232 switch (count($data)) {
234 $data = $defaultValue;
244 * Get a property from an SAML response.
245 * Handles properties potentially being an array.
247 protected function getSamlResponseAttribute(array $samlAttributes, string $propertyKey, $defaultValue)
249 if (isset($samlAttributes[$propertyKey])) {
250 return $this->simplifyValue($samlAttributes[$propertyKey], $defaultValue);
253 return $defaultValue;
257 * Register a user that is authenticated but not already registered.
259 protected function registerUser(array $userDetails): User
261 // Create an array of the user data to create a new user instance
263 'name' => $userDetails['name'],
264 'email' => $userDetails['email'],
265 'password' => Str::random(32),
266 'external_auth_id' => $userDetails['external_id'],
267 'email_confirmed' => true,
270 $existingUser = $this->user->newQuery()->where('email', '=', $userDetails['email'])->first();
272 throw new SamlException(trans('errors.saml_email_exists', ['email' => $userDetails['email']]));
275 $user = $this->user->forceCreate($userData);
276 $this->userRepo->attachDefaultRole($user);
277 $this->userRepo->downloadAndAssignUserAvatar($user);
282 * Get the user from the database for the specified details.
284 protected function getOrRegisterUser(array $userDetails): ?User
286 $isRegisterEnabled = $this->config['auto_register'] === true;
288 ->where('external_auth_id', $userDetails['external_id'])
291 if ($user === null && $isRegisterEnabled) {
292 $user = $this->registerUser($userDetails);
299 * Process the SAML response for a user. Login the user when
300 * they exist, optionally registering them automatically.
301 * @throws SamlException
302 * @throws JsonDebugException
304 public function processLoginCallback(string $samlID, array $samlAttributes): User
306 $userDetails = $this->getUserDetails($samlID, $samlAttributes);
307 $isLoggedIn = auth()->check();
309 if ($this->config['dump_user_details']) {
310 throw new JsonDebugException([
311 'attrs_from_idp' => $samlAttributes,
312 'attrs_after_parsing' => $userDetails,
317 throw new SamlException(trans('errors.saml_already_logged_in'), '/login');
320 $user = $this->getOrRegisterUser($userDetails);
321 if ($user === null) {
322 throw new SamlException(trans('errors.saml_user_not_registered', ['name' => $userDetails['external_id']]), '/login');
325 if ($this->shouldSyncGroups()) {
326 $groups = $this->getUserGroups($samlAttributes);
327 $this->syncWithGroups($user, $groups);
330 auth()->login($user);