1 package org.collectionspace.authentication.spring;
3 import java.util.LinkedHashMap;
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;
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.
19 public class CSpaceUserAuthenticationConverter implements UserAuthenticationConverter {
21 private UserDetailsService userDetailsService;
24 * Creates a converter that uses the given UserDetailsService when extracting
25 * the authentication information.
27 * @param userDetailsService the UserDetailsService to use
29 public CSpaceUserAuthenticationConverter(UserDetailsService userDetailsService) {
30 this.userDetailsService = userDetailsService;
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.
39 Map<String, Object> response = new LinkedHashMap<String, Object>();
41 response.put(USERNAME, userAuthentication.getName());
47 public Authentication extractAuthentication(Map<String, ?> map) {
48 if (!map.containsKey(USERNAME) || userDetailsService == null) {
52 String username = (String) map.get(USERNAME);
55 UserDetails user = userDetailsService.loadUserByUsername(username);
57 return new UsernamePasswordAuthenticationToken(user, "N/A", user.getAuthorities());
59 catch(UsernameNotFoundException e) {