]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3d81539a61ec4868df772f484172db230cc0d02b
[tmp/jakarta-migration.git] /
1 package org.collectionspace.authentication.spring;
2
3 import java.util.LinkedHashMap;
4 import java.util.Map;
5
6 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7 import org.springframework.security.core.Authentication;
8 import org.springframework.security.core.userdetails.UserDetails;
9 import org.springframework.security.core.userdetails.UserDetailsService;
10 import org.springframework.security.core.userdetails.UsernameNotFoundException;
11 import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
12
13 /**
14  * Converter for CSpace user authentication information to and from Maps.
15  * This is used to serialize/deserialize user information to/from JWTs.
16  * When extracting the user authentication from a map, only the username
17  * is required. The full user information is retrieved from a UserDetailsService.
18  */
19 public class CSpaceUserAuthenticationConverter implements UserAuthenticationConverter {
20
21     private UserDetailsService userDetailsService;
22
23     /**
24      * Creates a converter that uses the given UserDetailsService when extracting
25      * the authentication information.
26      * 
27      * @param userDetailsService the UserDetailsService to use
28      */
29     public CSpaceUserAuthenticationConverter(UserDetailsService userDetailsService) {
30         this.userDetailsService = userDetailsService;
31     }
32     
33     @Override
34     public Map<String, ?> convertUserAuthentication(Authentication userAuthentication) {
35         // In extractAuthentication we use a UserDetailsService to look up
36         // the user's roles and tenants, so there's no need to serialize
37         // those. We just need the username.
38         
39         Map<String, Object> response = new LinkedHashMap<String, Object>();
40         
41         response.put(USERNAME, userAuthentication.getName());
42         
43         return response;
44     }
45
46     @Override
47     public Authentication extractAuthentication(Map<String, ?> map) {
48         if (!map.containsKey(USERNAME) || userDetailsService == null) {
49             return null;
50         }
51         
52         String username = (String) map.get(USERNAME);
53
54         try {
55             UserDetails user = userDetailsService.loadUserByUsername(username);
56             
57             return new UsernamePasswordAuthenticationToken(user, "N/A", user.getAuthorities());
58         }
59         catch(UsernameNotFoundException e) {
60             return null;
61         }
62     }
63 }