1 package cn.home1.oss.lib.security.api;
2
3 import static java.util.stream.Collectors.toSet;
4
5 import com.google.common.collect.ImmutableMap;
6
7 import cn.home1.oss.lib.common.Defaults;
8 import cn.home1.oss.lib.security.internal.BaseGrantedAuthority;
9
10 import org.springframework.security.core.Authentication;
11 import org.springframework.security.core.GrantedAuthority;
12 import org.springframework.security.oauth2.provider.OAuth2Authentication;
13 import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
14
15 import java.security.Principal;
16 import java.util.Collection;
17 import java.util.Map;
18 import java.util.Set;
19
20
21
22
23 @SuppressWarnings({"PMD.AbstractNaming", "PMD.AbstractClassWithoutAbstractMethod"})
24 abstract class OAuth2Utils {
25
26 private OAuth2Utils() {
27 }
28
29 static Boolean isOAuth2Authentication(final Principal principal) {
30 return principal instanceof OAuth2Authentication;
31 }
32
33 static GenericUser fromOAuth2Authentication(final Principal principal) {
34 final GenericUser result;
35
36 final OAuth2Authentication oauth2Authentication = (OAuth2Authentication) principal;
37 final Authentication auth = oauth2Authentication.getUserAuthentication();
38
39 if (oauth2Authentication.isClientOnly() || auth == null || auth.getDetails() == null) {
40 result = null;
41 } else {
42 final boolean accountNonExpired = true;
43 final boolean accountNonLocked = true;
44 @SuppressWarnings("unchecked")
45 final Map<String, Object> details = (Map<String, Object>) auth.getDetails();
46 @SuppressWarnings("unchecked")
47 final Set<GrantedAuthority> authorities =
48 ((Collection<Map<String, String>>) details.get("authorities")).stream()
49 .map(authority -> new BaseGrantedAuthority(authority.get("authority")))
50 .collect(toSet());
51 final boolean credentialsNonExpired = true;
52 final boolean enabled = true;
53 final String password = System.getProperty("blankPassword", "");
54 final String username = auth.getPrincipal().toString();
55 final String uuid = ((OAuth2AuthenticationDetails) oauth2Authentication.getDetails()).getTokenValue();
56
57 result = new GenericUser(accountNonExpired, accountNonLocked, authorities, credentialsNonExpired,
58 enabled, password, username, ImmutableMap.of(),
59 Defaults.now(), uuid);
60 }
61
62 return result;
63 }
64 }