1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.spring.security.ldaptive.authentication;
18
19 import static java.util.Objects.isNull;
20 import static java.util.Objects.nonNull;
21 import static java.util.Objects.requireNonNullElseGet;
22 import static org.springframework.util.ObjectUtils.isEmpty;
23
24 import java.util.Collection;
25 import java.util.Optional;
26 import java.util.stream.Stream;
27 import lombok.AccessLevel;
28 import lombok.Getter;
29 import lombok.Setter;
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.bremersee.ldaptive.DefaultLdaptiveErrorHandler;
33 import org.bremersee.ldaptive.LdaptiveTemplate;
34 import org.bremersee.spring.security.ldaptive.authentication.provider.NoAccountControlEvaluator;
35 import org.bremersee.spring.security.ldaptive.userdetails.LdaptiveRememberMeTokenProvider;
36 import org.bremersee.spring.security.ldaptive.userdetails.LdaptiveUserDetails;
37 import org.bremersee.spring.security.ldaptive.userdetails.LdaptiveUserDetailsService;
38 import org.jspecify.annotations.NonNull;
39 import org.ldaptive.BindConnectionInitializer;
40 import org.ldaptive.BindOperation;
41 import org.ldaptive.BindResponse;
42 import org.ldaptive.CompareRequest;
43 import org.ldaptive.ConnectionConfig;
44 import org.ldaptive.ConnectionFactory;
45 import org.ldaptive.DefaultConnectionFactory;
46 import org.ldaptive.LdapException;
47 import org.ldaptive.SimpleBindRequest;
48 import org.ldaptive.SingleConnectionFactory;
49 import org.springframework.context.MessageSource;
50 import org.springframework.context.MessageSourceAware;
51 import org.springframework.context.support.MessageSourceAccessor;
52 import org.springframework.core.convert.converter.Converter;
53 import org.springframework.security.authentication.AccountExpiredException;
54 import org.springframework.security.authentication.AuthenticationManager;
55 import org.springframework.security.authentication.AuthenticationProvider;
56 import org.springframework.security.authentication.BadCredentialsException;
57 import org.springframework.security.authentication.CredentialsExpiredException;
58 import org.springframework.security.authentication.DisabledException;
59 import org.springframework.security.authentication.LockedException;
60 import org.springframework.security.authentication.RememberMeAuthenticationToken;
61 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
62 import org.springframework.security.core.Authentication;
63 import org.springframework.security.core.AuthenticationException;
64 import org.springframework.security.core.SpringSecurityMessageSource;
65 import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
66 import org.springframework.security.crypto.password.PasswordEncoder;
67 import org.springframework.util.Assert;
68
69
70
71
72
73
74 public class LdaptiveAuthenticationManager
75 implements AuthenticationManager, AuthenticationProvider, MessageSourceAware {
76
77
78
79
80 protected final Log logger = LogFactory.getLog(this.getClass());
81
82
83
84
85 @Getter(AccessLevel.PROTECTED)
86 private final LdaptiveAuthenticationProperties authenticationProperties;
87
88
89
90
91 @Getter(AccessLevel.PROTECTED)
92 private final String rememberMeKey;
93
94
95
96
97 @Getter(AccessLevel.PROTECTED)
98 private final LdaptiveTemplate applicationLdaptiveTemplate;
99
100
101
102
103 @Getter(AccessLevel.PROTECTED)
104 @Setter
105 private PasswordEncoder passwordEncoder;
106
107
108
109
110 @Getter(AccessLevel.PROTECTED)
111 private AccountControlEvaluator accountControlEvaluator;
112
113
114
115
116 @Getter(AccessLevel.PROTECTED)
117 @Setter
118 private GrantedAuthoritiesMapper grantedAuthoritiesMapper;
119
120
121
122
123 @Getter(AccessLevel.PROTECTED)
124 @Setter
125 private LdaptiveRememberMeTokenProvider passwordProvider;
126
127
128
129
130 @Getter(AccessLevel.PROTECTED)
131 @Setter
132 private Converter<LdaptiveUserDetails, LdaptiveAuthentication> tokenConverter;
133
134
135
136
137 @Getter(AccessLevel.PROTECTED)
138 private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
139
140
141
142
143
144
145
146
147 public LdaptiveAuthenticationManager(
148 ConnectionConfig connectionConfig,
149 LdaptiveAuthenticationProperties authenticationProperties,
150 String rememberMeKey) {
151 this(new DefaultConnectionFactory(connectionConfig), authenticationProperties, rememberMeKey);
152 }
153
154
155
156
157
158
159
160
161 public LdaptiveAuthenticationManager(
162 ConnectionFactory connectionFactory,
163 LdaptiveAuthenticationProperties authenticationProperties,
164 String rememberMeKey) {
165 this(new LdaptiveTemplate(connectionFactory), authenticationProperties, rememberMeKey);
166 }
167
168
169
170
171
172
173
174
175 public LdaptiveAuthenticationManager(
176 LdaptiveTemplate applicationLdaptiveTemplate,
177 LdaptiveAuthenticationProperties authenticationProperties,
178 String rememberMeKey) {
179
180 this.applicationLdaptiveTemplate = applicationLdaptiveTemplate;
181 Assert.notNull(getApplicationLdaptiveTemplate(), "Application ldaptive template is required.");
182 this.authenticationProperties = authenticationProperties;
183 Assert.notNull(getAuthenticationProperties(), "Authentication properties are required.");
184 this.rememberMeKey = rememberMeKey;
185
186
187 if (isNull(getAuthenticationProperties().getAccountControlEvaluator())) {
188 setAccountControlEvaluator(new NoAccountControlEvaluator());
189 } else {
190 setAccountControlEvaluator(getAuthenticationProperties().getAccountControlEvaluator().get());
191 }
192 }
193
194
195
196
197
198
199 public void setAccountControlEvaluator(
200 AccountControlEvaluator accountControlEvaluator) {
201 if (nonNull(accountControlEvaluator)) {
202 this.accountControlEvaluator = accountControlEvaluator;
203 }
204 }
205
206 @Override
207 public void setMessageSource(@NonNull MessageSource messageSource) {
208 this.messages = new MessageSourceAccessor(messageSource);
209 }
210
211
212
213
214 public void init() {
215 if (!isSimpleBindAuthentication() && isNull(getPasswordEncoder())) {
216 throw new IllegalStateException(String.format("A password attribute is set (%s) but no "
217 + "password encoder is present. Either delete the password attribute to perform a "
218 + "bind to authenticate or set a password encoder.",
219 getAuthenticationProperties().getPasswordAttribute()));
220 }
221 }
222
223 @Override
224 public boolean supports(@NonNull Class<?> authentication) {
225 return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)
226 || isRememberMeAuthentication(authentication);
227 }
228
229 private boolean isRememberMeAuthentication(Class<?> authentication) {
230 return !isEmpty(getRememberMeKey())
231 && RememberMeAuthenticationToken.class.isAssignableFrom(authentication);
232 }
233
234
235
236
237
238
239
240 protected boolean rememberMeKeyMatches(RememberMeAuthenticationToken authentication) {
241 return Optional.ofNullable(getRememberMeKey())
242 .filter(key -> key.hashCode() == authentication.getKeyHash())
243 .isPresent();
244 }
245
246 @NonNull
247 @Override
248 public Authentication authenticate(Authentication authentication)
249 throws AuthenticationException {
250
251 if (!supports(authentication.getClass())) {
252 logger.debug(String.format("Authentication [%s] is not supported.",
253 authentication.getClass().getName()));
254
255 return null;
256 }
257 if (authentication instanceof RememberMeAuthenticationToken rma) {
258 logger.debug("Remember me authentication token detected.");
259 if (!rememberMeKeyMatches(rma)) {
260 var m = "The presented remember me authentication token does not contain the expected key.";
261 logger.debug(m);
262 throw new BadCredentialsException(getMessages()
263 .getMessage("RememberMeAuthenticationProvider.incorrectKey", m));
264 }
265 return rma;
266 }
267
268 String name = getName(authentication);
269 logger.debug("Authenticating user '" + name + "' ...");
270 String password = Optional.ofNullable(authentication.getCredentials())
271 .map(String::valueOf)
272 .orElseThrow(() -> new BadCredentialsException("Password is required."));
273
274 LdaptiveUserDetails userDetails;
275 if (getApplicationLdaptiveTemplate().hasBindConnectionInitializer()) {
276 logger.debug("Using existing bind credentials to obtain the user.");
277 userDetails = getUserDetailsService().loadUserByUsername(name);
278 checkPassword(userDetails.getDn(), password);
279 } else {
280 logger.debug("Creating bind with credentials of the user.");
281 checkPassword(name, password);
282 logger.debug("Using bind credentials of the user to obtain it's information.");
283 userDetails = getUserDetailsService(name, password).loadUserByUsername(name);
284 }
285 logger.debug(String.format("User with username '%s' and dn '%s' successfully loaded.",
286 userDetails.getUsername(), userDetails.getDn()));
287 checkUsername(userDetails.getUsername());
288 checkAccountControl(userDetails);
289 logger.debug(String.format("User with username '%s' successfully validated.",
290 userDetails.getUsername()));
291
292 LdaptiveAuthentication token;
293 if (nonNull(getTokenConverter())) {
294 token = getTokenConverter().convert(userDetails);
295 } else {
296 token = new LdaptiveAuthenticationToken(userDetails);
297 }
298 logger.debug(String.format("User with username '%s' has roles: %s",
299 userDetails.getUsername(), token.getGrantedAuthorityNames()));
300 return token;
301 }
302
303
304
305
306
307
308
309 protected String getName(Authentication authentication) {
310 Object principal = authentication.getPrincipal();
311 if (principal instanceof LdaptiveUserDetails ldaptiveUserDetails) {
312 return requireNonNullElseGet(ldaptiveUserDetails.getDn(), authentication::getName);
313 }
314 return authentication.getName();
315 }
316
317
318
319
320
321
322 public LdaptiveUserDetailsService getUserDetailsService() {
323 return getUserDetailsService(getApplicationLdaptiveTemplate());
324 }
325
326
327
328
329
330
331
332
333 protected LdaptiveUserDetailsService getUserDetailsService(String userDn, String password) {
334 return getUserDetailsService(getLdaptiveTemplate(userDn, password));
335 }
336
337
338
339
340
341
342
343 protected LdaptiveUserDetailsService getUserDetailsService(LdaptiveTemplate ldaptiveTemplate) {
344 LdaptiveUserDetailsService userDetailsService = new LdaptiveUserDetailsService(
345 getAuthenticationProperties(), ldaptiveTemplate);
346 userDetailsService.setAccountControlEvaluator(getAccountControlEvaluator());
347 userDetailsService.setGrantedAuthoritiesMapper(getGrantedAuthoritiesMapper());
348 userDetailsService.setRememberMeTokenProvider(getPasswordProvider());
349 return userDetailsService;
350 }
351
352
353
354
355
356
357
358
359 protected LdaptiveTemplate getLdaptiveTemplate(String userDn, String password) {
360 ConnectionConfig connectionConfig = ConnectionConfig
361 .copy(getApplicationLdaptiveTemplate().getConnectionFactory().getConnectionConfig());
362 connectionConfig.setConnectionInitializers(BindConnectionInitializer.builder()
363 .dn(userDn)
364 .credential(password)
365 .build());
366 return new LdaptiveTemplate(new DefaultConnectionFactory(connectionConfig));
367 }
368
369
370
371
372
373
374 protected boolean isSimpleBindAuthentication() {
375 return isNull(getAuthenticationProperties().getPasswordAttribute())
376 || getAuthenticationProperties().getPasswordAttribute().isBlank();
377 }
378
379
380
381
382
383
384
385 protected void checkPassword(String userDn, String password) {
386 if (isSimpleBindAuthentication()) {
387 checkPasswordWithSimpleBind(userDn, password);
388 } else {
389 checkPasswordWithCompareRequest(userDn, password);
390 }
391 }
392
393
394
395
396
397
398
399 protected void checkPasswordWithCompareRequest(String userDn, String password) {
400 Assert.notNull(getPasswordEncoder(), "No password encoder is present.");
401 boolean matches = getApplicationLdaptiveTemplate().compare(CompareRequest.builder()
402 .dn(userDn)
403 .name(getAuthenticationProperties().getPasswordAttribute())
404 .value(getPasswordEncoder().encode(password))
405 .build());
406 if (!matches) {
407 throw new BadCredentialsException("Password doesn't match.");
408 }
409 }
410
411
412
413
414
415
416
417 protected void checkPasswordWithSimpleBind(String userDn, String password) {
418 SingleConnectionFactory connectionFactory = getSingleConnectionFactory();
419 try {
420 connectionFactory.initialize();
421 BindOperation bind = getBindOperation(connectionFactory);
422 BindResponse response = bind.execute(SimpleBindRequest.builder()
423 .dn(userDn)
424 .password(password)
425 .build());
426 if (!response.isSuccess()) {
427 throw new BadCredentialsException("Password doesn't match.");
428 }
429
430 } catch (LdapException ldapException) {
431 new DefaultLdaptiveErrorHandler().handleError(ldapException);
432 } finally {
433 connectionFactory.close();
434 }
435 }
436
437
438
439
440
441
442 protected void checkUsername(String username) {
443 if (isRefusedUsername(username)) {
444 throw new DisabledException(String
445 .format("Username '%s' is refused by configuration.", username));
446 }
447 }
448
449
450
451
452
453
454
455 protected boolean isRefusedUsername(String username) {
456 if (isEmpty(username)) {
457 return true;
458 }
459 return Stream.ofNullable(getAuthenticationProperties().getRefusedUsernames())
460 .flatMap(Collection::stream)
461 .filter(refusedUsername -> !isEmpty(refusedUsername))
462 .anyMatch(refusedUsername -> refusedUsername.equalsIgnoreCase(username));
463 }
464
465
466
467
468
469
470 protected SingleConnectionFactory getSingleConnectionFactory() {
471 ConnectionConfig connectionConfig = ConnectionConfig
472 .copy(getApplicationLdaptiveTemplate().getConnectionFactory().getConnectionConfig());
473 connectionConfig.setConnectionInitializers();
474 return new SingleConnectionFactory(connectionConfig);
475 }
476
477
478
479
480
481
482
483 protected BindOperation getBindOperation(ConnectionFactory connectionFactory) {
484 return new BindOperation(connectionFactory);
485 }
486
487
488
489
490
491
492 protected void checkAccountControl(LdaptiveUserDetails user) {
493 if (!user.isEnabled()) {
494 throw new DisabledException("Account is disabled.");
495 }
496 if (!user.isAccountNonLocked()) {
497 throw new LockedException("Account is locked.");
498 }
499 if (!user.isAccountNonExpired()) {
500 throw new AccountExpiredException("Account is expired.");
501 }
502 if (!user.isCredentialsNonExpired()) {
503 throw new CredentialsExpiredException("Credentials are expired.");
504 }
505 }
506
507 }