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.boot.autoconfigure.security.authentication;
18  
19  import static java.util.Objects.nonNull;
20  import static java.util.Objects.requireNonNullElseGet;
21  import static org.springframework.util.ObjectUtils.isEmpty;
22  
23  import java.io.Serial;
24  import java.io.Serializable;
25  import java.security.Principal;
26  import java.util.ArrayList;
27  import java.util.Collection;
28  import java.util.LinkedHashMap;
29  import java.util.List;
30  import java.util.Map;
31  import java.util.stream.Collectors;
32  import java.util.stream.Stream;
33  import lombok.Data;
34  import lombok.EqualsAndHashCode;
35  import lombok.Getter;
36  import lombok.Setter;
37  import lombok.ToString;
38  import org.bremersee.spring.security.core.NormalizedPrincipalDetails;
39  import org.bremersee.spring.security.core.NormalizedUserDetails;
40  import org.springframework.boot.context.properties.ConfigurationProperties;
41  import org.springframework.security.core.authority.SimpleGrantedAuthority;
42  import org.springframework.security.crypto.factory.PasswordEncoderFactories;
43  import org.springframework.security.crypto.password.PasswordEncoder;
44  
45  /**
46   * The authentication properties.
47   *
48   * @author Christian Bremer
49   */
50  @ConfigurationProperties(prefix = "bremersee.authentication")
51  @Data
52  public class AuthenticationProperties {
53  
54    /**
55     * The remember-me properties.
56     */
57    private RememberMeProperties rememberMe = new RememberMeProperties();
58  
59    /**
60     * The jwt converter properties.
61     */
62    private JwtConverterProperties jwtConverter = new JwtConverterProperties();
63  
64    /**
65     * The ldaptive properties.
66     */
67    private LdaptiveProperties ldaptive = new LdaptiveProperties();
68  
69    /**
70     * The actuator properties.
71     */
72    private ActuatorProperties actuator = new ActuatorProperties();
73  
74    /**
75     * The in-memory properties.
76     */
77    private InMemoryProperties inMemory = new InMemoryProperties();
78  
79    /**
80     * Instantiates new authentication properties.
81     */
82    public AuthenticationProperties() {
83      super();
84    }
85  
86    /**
87     * The remember-me properties.
88     *
89     * @author Christian Bremer
90     */
91    @Data
92    public static class RememberMeProperties {
93  
94      /**
95       * The key.
96       */
97      private String key;
98  
99      /**
100      * Specifies whether remember-me is always activated.
101      */
102     private Boolean alwaysRemember;
103 
104     /**
105      * The cookie name.
106      */
107     private String cookieName;
108 
109     /**
110      * The cookie domain.
111      */
112     private String cookieDomain;
113 
114     /**
115      * Specifies whether to use secure cookie.
116      */
117     private Boolean useSecureCookie;
118 
119     /**
120      * The parameter name (default remember-me).
121      */
122     private String parameterName;
123 
124     /**
125      * The token validity in seconds (default two weeks).
126      */
127     private Integer tokenValiditySeconds;
128 
129     /**
130      * Instantiates new remember-me properties.
131      */
132     public RememberMeProperties() {
133       super();
134     }
135   }
136 
137   /**
138    * The jwt converter properties.
139    *
140    * @author Christian Bremer
141    */
142   @Data
143   public static class JwtConverterProperties {
144 
145     /**
146      * The json path to the username.
147      */
148     private String nameJsonPath = "$.sub"; // keycloak: $.preferred_username
149 
150     /**
151      * The json path to the first name.
152      */
153     private String firstNameJsonPath = "$.given_name";
154 
155     /**
156      * The json path to the last name.
157      */
158     private String lastNameJsonPath = "$.family_name";
159 
160     /**
161      * The json path to the email.
162      */
163     private String emailJsonPath = "$.email";
164 
165     /**
166      * The json path to the roles.
167      */
168     private String rolesJsonPath = "$.scope"; // keycloak: $.realm_access.roles
169 
170     /**
171      * Specifies whether the roles are represented as a json array or as a list separated by
172      * {@link #getRolesValueSeparator()}.
173      */
174     private boolean rolesValueList = false; // keycloak: true
175 
176     /**
177      * The roles separator to use if {@link #isRolesValueList()} is set to {@code false}.
178      */
179     private String rolesValueSeparator = " ";
180 
181     /**
182      * The default roles.
183      */
184     private List<String> defaultRoles = new ArrayList<>();
185 
186     /**
187      * The role mappings.
188      */
189     private List<SimpleMapping> roleMapping = new ArrayList<>();
190 
191     /**
192      * The role prefix (like 'ROLE_' or 'SCOPE_').
193      */
194     private String rolePrefix = "SCOPE_"; // keycloak: ROLE_
195 
196     /**
197      * The role case transformation.
198      */
199     private CaseTransformation roleCaseTransformation;
200 
201     /**
202      * The string replacements for roles.
203      */
204     private List<StringReplacement> roleStringReplacements;
205 
206     /**
207      * The json path to the groups.
208      */
209     private String groupsJsonPath = "$.groups";
210 
211     /**
212      * Specifies whether the groups are represented as a json array or as a list separated by
213      * {@link #getGroupsValueSeparator()}.
214      */
215     private boolean groupsValueList = false; // keycloak: true
216 
217     /**
218      * The groups separator to use if {@link #isGroupsValueList()} is set to {@code false}.
219      */
220     private String groupsValueSeparator = " ";
221 
222     /**
223      * The default groups.
224      */
225     private List<String> defaultGroups = new ArrayList<>();
226 
227     /**
228      * The group mappings.
229      */
230     private List<SimpleMapping> groupMapping = new ArrayList<>();
231 
232     /**
233      * The group prefix (like 'GROUP_').
234      */
235     private String groupPrefix = "";
236 
237     /**
238      * The group case transformation.
239      */
240     private CaseTransformation groupCaseTransformation;
241 
242     /**
243      * The string replacements for groups.
244      */
245     private List<StringReplacement> groupStringReplacements;
246 
247     /**
248      * Instantiates new jwt converter properties.
249      */
250     public JwtConverterProperties() {
251       super();
252     }
253 
254     /**
255      * To role mappings.
256      *
257      * @return the map
258      */
259     public Map<String, String> toRoleMappings() {
260       return Stream.ofNullable(getRoleMapping())
261           .flatMap(Collection::stream)
262           .collect(Collectors.toMap(
263               SimpleMapping::getSource,
264               SimpleMapping::getTarget,
265               (first, second) -> first,
266               LinkedHashMap::new));
267     }
268 
269     /**
270      * To group mappings.
271      *
272      * @return the map
273      */
274     public Map<String, String> toGroupMappings() {
275       return Stream.ofNullable(getGroupMapping())
276           .flatMap(Collection::stream)
277           .collect(Collectors.toMap(
278               SimpleMapping::getSource,
279               SimpleMapping::getTarget,
280               (first, second) -> first,
281               LinkedHashMap::new));
282     }
283 
284     /**
285      * To role string replacements.
286      *
287      * @return the map
288      */
289     public Map<String, String> toRoleStringReplacements() {
290       return Stream.ofNullable(getRoleStringReplacements())
291           .flatMap(Collection::stream)
292           .collect(Collectors.toMap(
293               StringReplacement::getRegex,
294               StringReplacement::getReplacement,
295               (first, second) -> first,
296               LinkedHashMap::new));
297     }
298 
299     /**
300      * To group string replacements.
301      *
302      * @return the map
303      */
304     public Map<String, String> toGroupStringReplacements() {
305       return Stream.ofNullable(getGroupStringReplacements())
306           .flatMap(Collection::stream)
307           .collect(Collectors.toMap(
308               StringReplacement::getRegex,
309               StringReplacement::getReplacement,
310               (first, second) -> first,
311               LinkedHashMap::new));
312     }
313 
314   }
315 
316   /**
317    * The ldaptive properties.
318    *
319    * @author Christian Bremer
320    */
321   @Data
322   public static class LdaptiveProperties {
323 
324     /**
325      * The ldap template with default configuration properties.
326      */
327     private Template template = Template.ACTIVE_DIRECTORY;
328 
329     /**
330      * The user base dn (like 'ou=people,dc=example,dc=org'). This value is always required.
331      */
332     private String userBaseDn;
333 
334     /**
335      * A list with refused usernames.
336      */
337     private List<String> refusedUsernames;
338 
339     /**
340      * The object class of the user (like 'inetOrgPerson'). The selected template contains a
341      * default.
342      */
343     private String userObjectClass;
344 
345     /**
346      * The username attribute of the user (like 'uid' or 'sAMAccountName'). The selected template
347      * contains a default.
348      */
349     private String usernameAttribute;
350 
351     /**
352      * The password attribute of the user (like 'userPassword'). If it is empty, a simple user bind
353      * will be done with the credentials of the user for authentication. If it is present, the
354      * connection to the ldap server must be done by a 'global' user and a password encoder that
355      * fits your requirements must be present. The default password encoder only supports SHA, that
356      * is insecure.
357      */
358     private String passwordAttribute;
359 
360     /**
361      * The password last set attribute (like 'pwdLastSet') can be used to activate the remember-me
362      * functionality.
363      */
364     private String passwordLastSetAttribute;
365 
366     /**
367      * The filter to find the user. If it is empty, it will be generated from 'userObjectClass' and
368      * 'usernameAttribute' like this '(&(objectClass=inetOrgPerson)(uid={0}))'.
369      */
370     private String userFindOneFilter;
371 
372     /**
373      * The scope to find a user. Default is 'one level'.
374      */
375     private SearchScope userFindOneSearchScope;
376 
377     /**
378      * The first name attribute of the user. Default is 'givenName'.
379      */
380     protected String firstNameAttribute;
381 
382     /**
383      * The last name attribute of the user. Default is 'sn'.
384      */
385     protected String lastNameAttribute;
386 
387     /**
388      * The email attribute of the user. Default is 'mail';
389      */
390     private String emailAttribute;
391 
392     /**
393      * The account control evaluator.
394      */
395     private AccountControlEvaluatorProperty accountControlEvaluator;
396 
397     /**
398      * The group fetch strategy.
399      */
400     private GroupFetchStrategy groupFetchStrategy;
401 
402     /**
403      * The member attribute.
404      */
405     private String memberAttribute;
406 
407     /**
408      * The group base dn (like 'ou=groups,dc=example,dc=org'). It's only required, if
409      * {@code groupFetchStrategy} is set to {@code GROUP_CONTAINS_USERS}.
410      */
411     private String groupBaseDn;
412 
413     /**
414      * The group search scope. It's only required, if {@code groupFetchStrategy} is set to
415      * {@code GROUP_CONTAINS_USERS},
416      */
417     private SearchScope groupSearchScope;
418 
419     /**
420      * The group object class. It's only required, if {@code groupFetchStrategy} is set to
421      * {@code GROUP_CONTAINS_USERS}
422      */
423     private String groupObjectClass;
424 
425     /**
426      * The group id attribute. It's only required, if {@code groupFetchStrategy} is set to
427      * {@code GROUP_CONTAINS_USERS}
428      */
429     private String groupIdAttribute;
430 
431     /**
432      * The group member attribute. It's only required, if {@code groupFetchStrategy} is set to
433      * {@code GROUP_CONTAINS_USERS}
434      */
435     private String groupMemberAttribute;
436 
437     /**
438      * The group member format. It's only required, if {@code groupFetchStrategy} is set to
439      * {@code GROUP_CONTAINS_USERS}
440      */
441     private String groupMemberFormat;
442 
443     /**
444      * The role mappings.
445      */
446     private List<SimpleMapping> roleMapping;
447 
448     /**
449      * The default roles.
450      */
451     private List<String> defaultRoles;
452 
453     /**
454      * The role prefix (like 'ROLE_').
455      */
456     private String rolePrefix;
457 
458     /**
459      * The role case transformation.
460      */
461     private CaseTransformation roleCaseTransformation;
462 
463     /**
464      * The string replacements for roles.
465      */
466     private List<StringReplacement> roleStringReplacements;
467 
468     /**
469      * Instantiates new ldaptive properties.
470      */
471     public LdaptiveProperties() {
472       super();
473     }
474 
475     /**
476      * The search scope.
477      */
478     public enum SearchScope {
479 
480       /**
481        * Base object search.
482        */
483       OBJECT,
484 
485       /**
486        * Single level search.
487        */
488       ONELEVEL,
489 
490       /**
491        * Whole subtree search.
492        */
493       SUBTREE,
494 
495       /**
496        * Subordinate subtree search. See draft-sermersheim-ldap-subordinate-scope.
497        */
498       SUBORDINATE
499     }
500 
501     /**
502      * The account control evaluator property.
503      */
504     public enum AccountControlEvaluatorProperty {
505 
506       /**
507        * The None.
508        */
509       NONE,
510 
511       /**
512        * The Active directory.
513        */
514       ACTIVE_DIRECTORY
515     }
516 
517     /**
518      * The group fetch strategy.
519      */
520     public enum GroupFetchStrategy {
521 
522       /**
523        * Groups will not be fetched.
524        */
525       NONE,
526 
527       /**
528        * User contains groups group-fetch strategy.
529        */
530       USER_CONTAINS_GROUPS,
531 
532       /**
533        * Group contains users group-fetch strategy.
534        */
535       GROUP_CONTAINS_USERS
536     }
537 
538     /**
539      * The templates for ldap authentication.
540      *
541      * @author Christian Bremer
542      */
543     public enum Template {
544 
545       /**
546        * Active directory template.
547        */
548       ACTIVE_DIRECTORY,
549 
550       /**
551        * Open ldap template.
552        */
553       OPEN_LDAP,
554 
555       /**
556        * User contains groups template.
557        */
558       USER_CONTAINS_GROUPS,
559 
560       /**
561        * Group contains users template.
562        */
563       GROUP_CONTAINS_USERS
564     }
565   }
566 
567   /**
568    * The simple mapping.
569    *
570    * @author Christian Bremer
571    */
572   @Data
573   public static class SimpleMapping {
574 
575     private String source;
576 
577     private String target;
578 
579     /**
580      * Instantiates a new simple mapping.
581      */
582     public SimpleMapping() {
583       super();
584     }
585   }
586 
587   /**
588    * The case transformation.
589    */
590   public enum CaseTransformation {
591 
592     /**
593      * None case transformation.
594      */
595     NONE,
596 
597     /**
598      * To upper case transformation.
599      */
600     TO_UPPER_CASE,
601 
602     /**
603      * To lower case transformation.
604      */
605     TO_LOWER_CASE
606   }
607 
608   /**
609    * The string replacement.
610    *
611    * @author Christian Bremer
612    */
613   @Data
614   public static class StringReplacement {
615 
616     /**
617      * The regular expression to which the string is to be matched. '{@code [- ]}' for example would
618      * replace every '-' and every space.
619      */
620     private String regex;
621 
622     /**
623      * The string to be substituted for each match.
624      */
625     private String replacement;
626 
627     /**
628      * Instantiates a new string replacement.
629      */
630     public StringReplacement() {
631       super();
632     }
633   }
634 
635   /**
636    * The actuator properties.
637    *
638    * @author Christian Bremer
639    */
640   @Data
641   public static class ActuatorProperties {
642 
643     private List<String> readRoles = new ArrayList<>();
644 
645     private List<String> writeRoles = new ArrayList<>();
646 
647     /**
648      * Instantiates actuator properties.
649      */
650     public ActuatorProperties() {
651       super();
652     }
653 
654     /**
655      * Gets read roles.
656      *
657      * @return the read roles
658      */
659     public List<String> getReadRoles() {
660       if (isEmpty(readRoles)) {
661         return List.of("ROLE_ADMIN", "ROLE_ACTUATOR", "ROLE_ACTUATOR_ADMIN");
662       }
663       return readRoles;
664     }
665 
666     /**
667      * Gets write roles.
668      *
669      * @return the write roles
670      */
671     public List<String> getWriteRoles() {
672       if (isEmpty(writeRoles)) {
673         return List.of("ROLE_ADMIN", "ROLE_ACTUATOR_ADMIN");
674       }
675       return writeRoles;
676     }
677   }
678 
679   /**
680    * The in-memory properties.
681    *
682    * @author Christian Bremer
683    */
684   @Data
685   public static class InMemoryProperties {
686 
687     /**
688      * Specifies whether an in-memory user details service should be created or not. Default is
689      * {@code false}.
690      */
691     private boolean enabled;
692 
693     /**
694      * The users.
695      */
696     private List<SimpleUser> users = new ArrayList<>();
697 
698     /**
699      * Build user details.
700      *
701      * @param passwordEncoder the password encoder
702      * @return the list
703      */
704     public List<NormalizedPrincipalDetails> buildUserDetails(PasswordEncoder passwordEncoder) {
705       PasswordEncoder encoder = requireNonNullElseGet(
706           passwordEncoder,
707           PasswordEncoderFactories::createDelegatingPasswordEncoder);
708       return getUsers().stream()
709           .map(user -> NormalizedUserDetails.builder()
710               .username(user.getName())
711               .password(nonNull(user.getPassword()) ? encoder.encode(user.getPassword()) : null)
712               .firstName(user.getFirstName())
713               .lastName(user.getLastName())
714               .email(user.getEmail())
715               .authorities(user.getAuthorities().stream()
716                   .map(SimpleGrantedAuthority::new)
717                   .toList())
718               .build())
719           .map(NormalizedPrincipalDetails.class::cast)
720           .toList();
721     }
722   }
723 
724   /**
725    * The simple user.
726    *
727    * @author Christian Bremer
728    */
729   @Getter
730   @Setter
731   @ToString(exclude = "password")
732   @EqualsAndHashCode(exclude = "password")
733   public static class SimpleUser implements Serializable, Principal {
734 
735     @Serial
736     private static final long serialVersionUID = -1393400622632455935L;
737 
738     /**
739      * The username.
740      */
741     private String name;
742 
743     /**
744      * The password.
745      */
746     private String password;
747 
748     /**
749      * The first name (optional).
750      */
751     private String firstName;
752 
753     /**
754      * The last name (optional).
755      */
756     private String lastName;
757 
758     /**
759      * The email (optional).
760      */
761     private String email;
762 
763     /**
764      * The granted authorities.
765      */
766     private List<String> authorities = new ArrayList<>();
767 
768     /**
769      * Instantiates a new simple user.
770      */
771     public SimpleUser() {
772       super();
773     }
774   }
775 
776 }