1
2
3
4
5
6
7
8
9
10
11
12
13
14 package org.springframework.security.oauth2.provider.token;
15
16 import java.util.Collection;
17 import java.util.LinkedHashMap;
18 import java.util.Map;
19
20 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
21 import org.springframework.security.core.Authentication;
22 import org.springframework.security.core.GrantedAuthority;
23 import org.springframework.security.core.authority.AuthorityUtils;
24 import org.springframework.security.core.userdetails.UserDetails;
25 import org.springframework.security.core.userdetails.UserDetailsService;
26 import org.springframework.util.StringUtils;
27
28
29
30
31
32
33
34
35 public class DefaultUserAuthenticationConverter implements UserAuthenticationConverter {
36
37 private Collection<? extends GrantedAuthority> defaultAuthorities;
38
39 private UserDetailsService userDetailsService;
40
41
42
43
44
45
46 public void setUserDetailsService(UserDetailsService userDetailsService) {
47 this.userDetailsService = userDetailsService;
48 }
49
50
51
52
53
54
55
56
57 public void setDefaultAuthorities(String[] defaultAuthorities) {
58 this.defaultAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
59 .arrayToCommaDelimitedString(defaultAuthorities));
60 }
61
62 public Map<String, ?> convertUserAuthentication(Authentication authentication) {
63 Map<String, Object> response = new LinkedHashMap<String, Object>();
64 response.put(USERNAME, authentication.getName());
65 if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
66 response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
67 }
68 return response;
69 }
70
71 public Authentication extractAuthentication(Map<String, ?> map) {
72 if (map.containsKey(USERNAME)) {
73 Object principal = map.get(USERNAME);
74 Collection<? extends GrantedAuthority> authorities = getAuthorities(map);
75 if (userDetailsService != null) {
76 UserDetails user = userDetailsService.loadUserByUsername((String) map.get(USERNAME));
77 authorities = user.getAuthorities();
78 principal = user;
79 }
80 return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
81 }
82 return null;
83 }
84
85 private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
86 if (!map.containsKey(AUTHORITIES)) {
87 return defaultAuthorities;
88 }
89 Object authorities = map.get(AUTHORITIES);
90 if (authorities instanceof String) {
91 return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
92 }
93 if (authorities instanceof Collection) {
94 return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils
95 .collectionToCommaDelimitedString((Collection<?>) authorities));
96 }
97 throw new IllegalArgumentException("Authorities must be either a String or a Collection");
98 }
99 }