View Javadoc
1   /*
2    * Copyright 2024-2026 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.userdetails;
18  
19  import static java.util.Objects.nonNull;
20  import static org.springframework.util.ObjectUtils.isEmpty;
21  
22  import java.util.Collection;
23  import java.util.Objects;
24  import java.util.Optional;
25  import java.util.Set;
26  import java.util.function.Predicate;
27  import java.util.regex.Pattern;
28  import java.util.stream.Collectors;
29  import java.util.stream.Stream;
30  import lombok.AccessLevel;
31  import lombok.Getter;
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.bremersee.ldaptive.LdaptiveAttribute;
35  import org.bremersee.ldaptive.LdaptiveTemplate;
36  import org.bremersee.spring.security.ldaptive.authentication.AccountControlEvaluator;
37  import org.bremersee.spring.security.ldaptive.authentication.LdaptiveAuthenticationProperties;
38  import org.bremersee.spring.security.ldaptive.authentication.provider.NoAccountControlEvaluator;
39  import org.jspecify.annotations.NonNull;
40  import org.ldaptive.FilterTemplate;
41  import org.ldaptive.LdapAttribute;
42  import org.ldaptive.LdapEntry;
43  import org.ldaptive.SearchRequest;
44  import org.ldaptive.dn.Dn;
45  import org.ldaptive.dn.NameValue;
46  import org.ldaptive.dn.RDn;
47  import org.springframework.security.core.GrantedAuthority;
48  import org.springframework.security.core.authority.SimpleGrantedAuthority;
49  import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
50  import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
51  import org.springframework.security.core.userdetails.UserDetailsService;
52  import org.springframework.security.core.userdetails.UsernameNotFoundException;
53  import org.springframework.util.Assert;
54  
55  /**
56   * The ldaptive user details service.
57   *
58   * @author Christian Bremer
59   */
60  @Getter(AccessLevel.PROTECTED)
61  public class LdaptiveUserDetailsService implements UserDetailsService {
62  
63    /**
64     * The constant USERNAME_PLACEHOLDER.
65     */
66    protected static final String USERNAME_PLACEHOLDER = "${username}";
67  
68    /**
69     * The logger.
70     */
71    private final Log logger = LogFactory.getLog(this.getClass());
72  
73    /**
74     * The authentication properties.
75     */
76    private final LdaptiveAuthenticationProperties authenticationProperties;
77  
78    /**
79     * The ldaptive template.
80     */
81    private final LdaptiveTemplate ldaptiveTemplate;
82  
83    /**
84     * The groups mapper.
85     */
86    private GrantedAuthoritiesMapper grantedAuthoritiesMapper;
87  
88    /**
89     * The account control evaluator.
90     */
91    private AccountControlEvaluator accountControlEvaluator = new NoAccountControlEvaluator();
92  
93    /**
94     * The remember-me token provider.
95     */
96    private LdaptiveRememberMeTokenProvider rememberMeTokenProvider;
97  
98    /**
99     * Instantiates a ldaptive user details service.
100    *
101    * @param authenticationProperties the authentication properties
102    * @param ldaptiveTemplate the ldaptive template
103    */
104   public LdaptiveUserDetailsService(
105       LdaptiveAuthenticationProperties authenticationProperties,
106       LdaptiveTemplate ldaptiveTemplate) {
107 
108     this.authenticationProperties = authenticationProperties;
109     this.ldaptiveTemplate = ldaptiveTemplate;
110     Assert.notNull(getAuthenticationProperties(), "Authentication properties are required.");
111     Assert.notNull(getLdaptiveTemplate(), "Ldaptive template is required.");
112     setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
113     if (nonNull(authenticationProperties.getAccountControlEvaluator())) {
114       setAccountControlEvaluator(authenticationProperties.getAccountControlEvaluator().get());
115     }
116     if (isEmpty(getAuthenticationProperties().getPasswordLastSetAttribute())) {
117       setRememberMeTokenProvider(
118           new LdaptiveEvaluatedRememberMeTokenProvider(getAccountControlEvaluator()));
119     } else {
120       setRememberMeTokenProvider(
121           new LdaptivePwdLastSetRememberMeTokenProvider(getAccountControlEvaluator(),
122               getAuthenticationProperties().getPasswordLastSetAttribute()));
123     }
124   }
125 
126   /**
127    * Sets groups mapper.
128    *
129    * @param grantedAuthoritiesMapper the groups mapper
130    */
131   public void setGrantedAuthoritiesMapper(
132       GrantedAuthoritiesMapper grantedAuthoritiesMapper) {
133     if (nonNull(grantedAuthoritiesMapper)) {
134       this.grantedAuthoritiesMapper = grantedAuthoritiesMapper;
135     }
136   }
137 
138   /**
139    * Sets account control evaluator.
140    *
141    * @param accountControlEvaluator the account control evaluator
142    */
143   public void setAccountControlEvaluator(
144       AccountControlEvaluator accountControlEvaluator) {
145     if (nonNull(accountControlEvaluator)) {
146       this.accountControlEvaluator = accountControlEvaluator;
147     }
148   }
149 
150   /**
151    * Sets remember-me token provider.
152    *
153    * @param rememberMeTokenProvider the remember-me token provider
154    */
155   public void setRememberMeTokenProvider(LdaptiveRememberMeTokenProvider rememberMeTokenProvider) {
156     if (nonNull(rememberMeTokenProvider)) {
157       this.rememberMeTokenProvider = rememberMeTokenProvider;
158     }
159   }
160 
161   @NonNull
162   @Override
163   public LdaptiveUserDetails loadUserByUsername(@NonNull String username) throws UsernameNotFoundException {
164     logger.debug(String.format("Loading user '%s' ...", username));
165     LdapEntry ldapEntry = findUser(username)
166         .orElseThrow(() -> new UsernameNotFoundException(String
167             .format("User '%s' was  not found.", username)));
168     Collection<? extends GrantedAuthority> authorities = getAuthorities(ldapEntry);
169     var userDetailsBuilder = LdaptiveUserDetails.builder()
170         .dn(ldapEntry.getDn())
171         .username(LdaptiveAttribute.define(getAuthenticationProperties().getUsernameAttribute())
172             .getValue(ldapEntry)
173             .orElse(username))
174         .password(getRememberMeTokenProvider().getRememberMeToken(ldapEntry))
175         .accountNonExpired(getAccountControlEvaluator().isAccountNonExpired(ldapEntry))
176         .accountNonLocked(getAccountControlEvaluator().isAccountNonLocked(ldapEntry))
177         .credentialsNonExpired(getAccountControlEvaluator().isCredentialsNonExpired(ldapEntry))
178         .enabled(getAccountControlEvaluator().isEnabled(ldapEntry))
179         .authorities(authorities);
180     LdaptiveAttribute.define(getAuthenticationProperties().getFirstNameAttribute())
181         .getValue(ldapEntry)
182         .ifPresent(userDetailsBuilder::firstName);
183     LdaptiveAttribute.define(getAuthenticationProperties().getLastNameAttribute())
184         .getValue(ldapEntry)
185         .ifPresent(userDetailsBuilder::lastName);
186     LdaptiveAttribute.define(getAuthenticationProperties().getEmailAttribute())
187         .getValue(ldapEntry)
188         .ifPresent(userDetailsBuilder::email);
189     return userDetailsBuilder.build();
190   }
191 
192   /**
193    * Determines whether the given username is a distinguished name or not.
194    *
195    * @param username the username
196    * @return {@code true} if the username is a distinguished name, otherwise {@code false}
197    */
198   protected boolean isDn(String username) {
199     try {
200       Dn baseDn = new Dn(getAuthenticationProperties().getUserBaseDn());
201       return Optional.ofNullable(username)
202           .map(Dn::new)
203           .filter(baseDn::isAncestor)
204           .isPresent();
205 
206     } catch (RuntimeException e) {
207       return false;
208     }
209   }
210 
211   /**
212    * Find user.
213    *
214    * @param username the username
215    * @return the user
216    */
217   public Optional<LdapEntry> findUser(String username) {
218     SearchRequest searchRequest = isDn(username)
219         ? SearchRequest.objectScopeSearchRequest(username)
220         : SearchRequest.builder()
221             .dn(getAuthenticationProperties().getUserBaseDn())
222             .filter(FilterTemplate.builder()
223                 .filter(getAuthenticationProperties().getUserFindOneFilter())
224                 .parameters(username)
225                 .build())
226             .scope(getAuthenticationProperties().getUserFindOneSearchScope())
227             .sizeLimit(1)
228             .build();
229     return getLdaptiveTemplate().findOne(searchRequest);
230   }
231 
232   /**
233    * Gets authorities.
234    *
235    * @param user the user
236    * @return the authorities
237    */
238   public Collection<GrantedAuthority> getAuthorities(LdapEntry user) {
239 
240     return switch (getAuthenticationProperties().getGroupFetchStrategy()) {
241       case NONE -> Set.of();
242       case USER_CONTAINS_GROUPS -> getAuthoritiesByGroupsInUser(user);
243       case GROUP_CONTAINS_USERS -> getAuthoritiesByGroupsWithUser(user);
244     };
245   }
246 
247   /**
248    * Gets roles by groups in user.
249    *
250    * @param user the user
251    * @return the roles by groups in user
252    */
253   protected Collection<GrantedAuthority> getAuthoritiesByGroupsInUser(LdapEntry user) {
254     Collection<GrantedAuthority> authorities = Stream.ofNullable(user)
255         .map(entry -> entry.getAttribute(getAuthenticationProperties().getMemberAttribute()))
256         .filter(Objects::nonNull)
257         .map(LdapAttribute::getStringValues)
258         .filter(Objects::nonNull)
259         .flatMap(Collection::stream)
260         .flatMap(memberOfValue -> getGroupName(memberOfValue).stream())
261         .map(SimpleGrantedAuthority::new)
262         .collect(Collectors.toSet());
263     return Set.copyOf(getGrantedAuthoritiesMapper().mapAuthorities(authorities));
264   }
265 
266   private static Optional<String> getGroupName(String groupNameOrGroupDn) {
267     return getDn(groupNameOrGroupDn)
268         .map(Dn::getRDn)
269         .map(RDn::getNameValue)
270         .map(NameValue::getStringValue)
271         .or(() -> Optional.ofNullable(groupNameOrGroupDn))
272         .filter(Predicate.not(String::isBlank));
273   }
274 
275   private static Optional<Dn> getDn(String dn) {
276     if (isEmpty(dn)) {
277       return Optional.empty();
278     }
279     try {
280       return Optional.of(new Dn(dn));
281     } catch (RuntimeException e) {
282       return Optional.empty();
283     }
284   }
285 
286   /**
287    * Gets roles by groups with user.
288    *
289    * @param user the user
290    * @return the roles by groups with user
291    */
292   protected Collection<GrantedAuthority> getAuthoritiesByGroupsWithUser(LdapEntry user) {
293     Collection<GrantedAuthority> authorities = getLdaptiveTemplate()
294         .findAll(
295             SearchRequest.builder()
296                 .dn(getAuthenticationProperties().getGroupBaseDn())
297                 .filter(FilterTemplate.builder()
298                     .filter(getAuthorityFilter(user))
299                     .build())
300                 .scope(getAuthenticationProperties().getGroupSearchScope())
301                 .build())
302         .stream()
303         .map(this::getAuthorityName)
304         .map(SimpleGrantedAuthority::new)
305         .collect(Collectors.toSet());
306     return Set.copyOf(getGrantedAuthoritiesMapper().mapAuthorities(authorities));
307   }
308 
309   /**
310    * Gets group filter.
311    *
312    * @param user the user
313    * @return the group filter
314    */
315   protected String getAuthorityFilter(LdapEntry user) {
316     String groupObjectClass = getAuthenticationProperties().getGroupObjectClass();
317     String groupMemberAttribute = getAuthenticationProperties().getGroupMemberAttribute();
318     String groupMemberValue;
319     String groupMemberFormat = getAuthenticationProperties().getGroupMemberFormat();
320     if (isEmpty(groupMemberFormat)) {
321       groupMemberValue = user.getDn();
322     } else {
323       String username = user.getAttribute(getAuthenticationProperties().getUsernameAttribute())
324           .getStringValue();
325       groupMemberValue = groupMemberFormat
326           .replaceFirst(Pattern.quote(USERNAME_PLACEHOLDER), username);
327     }
328     return String.format("(&(objectClass=%s)(%s=%s))",
329         groupObjectClass, groupMemberAttribute, groupMemberValue);
330   }
331 
332   /**
333    * Gets group name.
334    *
335    * @param group the group
336    * @return the group name
337    */
338   protected String getAuthorityName(LdapEntry group) {
339     String groupIdAttribute = getAuthenticationProperties().getGroupIdAttribute();
340     String fallback = getGroupName(group.getDn()).orElse(null);
341     if (isEmpty(groupIdAttribute)) {
342       return fallback;
343     }
344     return Optional.ofNullable(group.getAttribute(groupIdAttribute))
345         .map(LdapAttribute::getStringValue)
346         .orElse(fallback);
347   }
348 
349 }