View Javadoc
1   /*
2    * Copyright 2014 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
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   * The ldaptive authentication manager.
71   *
72   * @author Christian Bremer
73   */
74  public class LdaptiveAuthenticationManager
75      implements AuthenticationManager, AuthenticationProvider, MessageSourceAware {
76  
77    /**
78     * The Logger.
79     */
80    protected final Log logger = LogFactory.getLog(this.getClass());
81  
82    /**
83     * The authentication properties.
84     */
85    @Getter(AccessLevel.PROTECTED)
86    private final LdaptiveAuthenticationProperties authenticationProperties;
87  
88    /**
89     * The remember-me key.
90     */
91    @Getter(AccessLevel.PROTECTED)
92    private final String rememberMeKey;
93  
94    /**
95     * The application ldaptive template.
96     */
97    @Getter(AccessLevel.PROTECTED)
98    private final LdaptiveTemplate applicationLdaptiveTemplate;
99  
100   /**
101    * The password encoder.
102    */
103   @Getter(AccessLevel.PROTECTED)
104   @Setter
105   private PasswordEncoder passwordEncoder;
106 
107   /**
108    * The account control evaluator.
109    */
110   @Getter(AccessLevel.PROTECTED)
111   private AccountControlEvaluator accountControlEvaluator;
112 
113   /**
114    * The groups mapper.
115    */
116   @Getter(AccessLevel.PROTECTED)
117   @Setter
118   private GrantedAuthoritiesMapper grantedAuthoritiesMapper;
119 
120   /**
121    * The remember-me token provider.
122    */
123   @Getter(AccessLevel.PROTECTED)
124   @Setter
125   private LdaptiveRememberMeTokenProvider passwordProvider;
126 
127   /**
128    * The token converter.
129    */
130   @Getter(AccessLevel.PROTECTED)
131   @Setter
132   private Converter<LdaptiveUserDetails, LdaptiveAuthentication> tokenConverter;
133 
134   /**
135    * The message source.
136    */
137   @Getter(AccessLevel.PROTECTED)
138   private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
139 
140   /**
141    * Instantiates a new ldaptive authentication manager.
142    *
143    * @param connectionConfig the connection config
144    * @param authenticationProperties the authentication properties
145    * @param rememberMeKey the remember me key
146    */
147   public LdaptiveAuthenticationManager(
148       ConnectionConfig connectionConfig,
149       LdaptiveAuthenticationProperties authenticationProperties,
150       String rememberMeKey) {
151     this(new DefaultConnectionFactory(connectionConfig), authenticationProperties, rememberMeKey);
152   }
153 
154   /**
155    * Instantiates a new ldaptive authentication manager.
156    *
157    * @param connectionFactory the connection factory
158    * @param authenticationProperties the authentication properties
159    * @param rememberMeKey the remember me key
160    */
161   public LdaptiveAuthenticationManager(
162       ConnectionFactory connectionFactory,
163       LdaptiveAuthenticationProperties authenticationProperties,
164       String rememberMeKey) {
165     this(new LdaptiveTemplate(connectionFactory), authenticationProperties, rememberMeKey);
166   }
167 
168   /**
169    * Instantiates a new ldaptive authentication manager.
170    *
171    * @param applicationLdaptiveTemplate the application ldaptive template
172    * @param authenticationProperties the authentication properties
173    * @param rememberMeKey the remember me key
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     // accountControlEvaluator
187     if (isNull(getAuthenticationProperties().getAccountControlEvaluator())) {
188       setAccountControlEvaluator(new NoAccountControlEvaluator());
189     } else {
190       setAccountControlEvaluator(getAuthenticationProperties().getAccountControlEvaluator().get());
191     }
192   }
193 
194   /**
195    * Sets account control evaluator.
196    *
197    * @param accountControlEvaluator the account control evaluator
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    * Init.
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    * Remember me key matches given authentication.
236    *
237    * @param authentication the authentication
238    * @return the boolean
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       //noinspection DataFlowIssue
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    * Gets name from authentication.
305    *
306    * @param authentication the authentication
307    * @return the name
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    * Gets user details service.
319    *
320    * @return the user details service
321    */
322   public LdaptiveUserDetailsService getUserDetailsService() {
323     return getUserDetailsService(getApplicationLdaptiveTemplate());
324   }
325 
326   /**
327    * Gets user details service.
328    *
329    * @param userDn the user dn
330    * @param password the password
331    * @return the user details service
332    */
333   protected LdaptiveUserDetailsService getUserDetailsService(String userDn, String password) {
334     return getUserDetailsService(getLdaptiveTemplate(userDn, password));
335   }
336 
337   /**
338    * Gets user details service.
339    *
340    * @param ldaptiveTemplate the ldaptive template
341    * @return the user details service
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    * Gets ldaptive template.
354    *
355    * @param userDn the user dn
356    * @param password the password
357    * @return the ldaptive template
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    * Determines whether to bind with username and password or to compare the passwords.
371    *
372    * @return the boolean
373    */
374   protected boolean isSimpleBindAuthentication() {
375     return isNull(getAuthenticationProperties().getPasswordAttribute())
376         || getAuthenticationProperties().getPasswordAttribute().isBlank();
377   }
378 
379   /**
380    * Check password.
381    *
382    * @param userDn the distinguished name of the user
383    * @param password the password
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    * Check password with compare request.
395    *
396    * @param userDn the distinguished name of the user
397    * @param password the password
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    * Check password with simple bind.
413    *
414    * @param userDn the distinguished name of the user
415    * @param password the password
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    * Check username.
439    *
440    * @param username the username
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    * Determines whether the username is refused by configuration.
451    *
452    * @param username the username
453    * @return {@code true} if the username is refused, otherwise {@code false}
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    * Gets single connection factory.
467    *
468    * @return the single connection factory
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    * Gets bind operation.
479    *
480    * @param connectionFactory the connection factory
481    * @return the bind operation
482    */
483   protected BindOperation getBindOperation(ConnectionFactory connectionFactory) {
484     return new BindOperation(connectionFactory);
485   }
486 
487   /**
488    * Check account control.
489    *
490    * @param user the user
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 }