|
| 1 | +package cn.zhangxd.svca.config; |
| 2 | + |
| 3 | +import org.apache.commons.logging.Log; |
| 4 | +import org.apache.commons.logging.LogFactory; |
| 5 | +import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor; |
| 6 | +import org.springframework.boot.autoconfigure.security.oauth2.resource.FixedAuthoritiesExtractor; |
| 7 | +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 8 | +import org.springframework.security.core.AuthenticationException; |
| 9 | +import org.springframework.security.core.GrantedAuthority; |
| 10 | +import org.springframework.security.oauth2.client.OAuth2RestOperations; |
| 11 | +import org.springframework.security.oauth2.client.OAuth2RestTemplate; |
| 12 | +import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails; |
| 13 | +import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; |
| 14 | +import org.springframework.security.oauth2.common.OAuth2AccessToken; |
| 15 | +import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; |
| 16 | +import org.springframework.security.oauth2.provider.OAuth2Authentication; |
| 17 | +import org.springframework.security.oauth2.provider.OAuth2Request; |
| 18 | +import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; |
| 19 | + |
| 20 | +import java.util.*; |
| 21 | + |
| 22 | +/** |
| 23 | + * Extended implementation of {@link org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices} |
| 24 | + * |
| 25 | + * By default, it designed to return only user details. This class provides {@link #getRequest(Map)} method, which |
| 26 | + * returns clientId and scope of calling service. This information used in controller's security checks. |
| 27 | + */ |
| 28 | + |
| 29 | +public class CustomUserInfoTokenServices implements ResourceServerTokenServices { |
| 30 | + |
| 31 | + protected final Log logger = LogFactory.getLog(getClass()); |
| 32 | + |
| 33 | + private static final String[] PRINCIPAL_KEYS = new String[] { "user", "username", |
| 34 | + "userid", "user_id", "login", "id", "name" }; |
| 35 | + |
| 36 | + private final String userInfoEndpointUrl; |
| 37 | + |
| 38 | + private final String clientId; |
| 39 | + |
| 40 | + private OAuth2RestOperations restTemplate; |
| 41 | + |
| 42 | + private String tokenType = DefaultOAuth2AccessToken.BEARER_TYPE; |
| 43 | + |
| 44 | + private AuthoritiesExtractor authoritiesExtractor = new FixedAuthoritiesExtractor(); |
| 45 | + |
| 46 | + public CustomUserInfoTokenServices(String userInfoEndpointUrl, String clientId) { |
| 47 | + this.userInfoEndpointUrl = userInfoEndpointUrl; |
| 48 | + this.clientId = clientId; |
| 49 | + } |
| 50 | + |
| 51 | + public void setTokenType(String tokenType) { |
| 52 | + this.tokenType = tokenType; |
| 53 | + } |
| 54 | + |
| 55 | + public void setRestTemplate(OAuth2RestOperations restTemplate) { |
| 56 | + this.restTemplate = restTemplate; |
| 57 | + } |
| 58 | + |
| 59 | + public void setAuthoritiesExtractor(AuthoritiesExtractor authoritiesExtractor) { |
| 60 | + this.authoritiesExtractor = authoritiesExtractor; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public OAuth2Authentication loadAuthentication(String accessToken) |
| 65 | + throws AuthenticationException, InvalidTokenException { |
| 66 | + Map<String, Object> map = getMap(this.userInfoEndpointUrl, accessToken); |
| 67 | + if (map.containsKey("error")) { |
| 68 | + this.logger.debug("userinfo returned error: " + map.get("error")); |
| 69 | + throw new InvalidTokenException(accessToken); |
| 70 | + } |
| 71 | + return extractAuthentication(map); |
| 72 | + } |
| 73 | + |
| 74 | + private OAuth2Authentication extractAuthentication(Map<String, Object> map) { |
| 75 | + Object principal = getPrincipal(map); |
| 76 | + OAuth2Request request = getRequest(map); |
| 77 | + List<GrantedAuthority> authorities = this.authoritiesExtractor |
| 78 | + .extractAuthorities(map); |
| 79 | + UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( |
| 80 | + principal, "N/A", authorities); |
| 81 | + token.setDetails(map); |
| 82 | + return new OAuth2Authentication(request, token); |
| 83 | + } |
| 84 | + |
| 85 | + private Object getPrincipal(Map<String, Object> map) { |
| 86 | + for (String key : PRINCIPAL_KEYS) { |
| 87 | + if (map.containsKey(key)) { |
| 88 | + return map.get(key); |
| 89 | + } |
| 90 | + } |
| 91 | + return "unknown"; |
| 92 | + } |
| 93 | + |
| 94 | + @SuppressWarnings({ "unchecked" }) |
| 95 | + private OAuth2Request getRequest(Map<String, Object> map) { |
| 96 | + Map<String, Object> request = (Map<String, Object>) map.get("oauth2Request"); |
| 97 | + |
| 98 | + String clientId = (String) request.get("clientId"); |
| 99 | + Set<String> scope = new LinkedHashSet<>(request.containsKey("scope") ? |
| 100 | + (Collection<String>) request.get("scope") : Collections.<String>emptySet()); |
| 101 | + |
| 102 | + return new OAuth2Request(null, clientId, null, true, new HashSet<>(scope), |
| 103 | + null, null, null, null); |
| 104 | + } |
| 105 | + |
| 106 | + @Override |
| 107 | + public OAuth2AccessToken readAccessToken(String accessToken) { |
| 108 | + throw new UnsupportedOperationException("Not supported: read access token"); |
| 109 | + } |
| 110 | + |
| 111 | + @SuppressWarnings({ "unchecked" }) |
| 112 | + private Map<String, Object> getMap(String path, String accessToken) { |
| 113 | + this.logger.debug("Getting user info from: " + path); |
| 114 | + try { |
| 115 | + OAuth2RestOperations restTemplate = this.restTemplate; |
| 116 | + if (restTemplate == null) { |
| 117 | + BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails(); |
| 118 | + resource.setClientId(this.clientId); |
| 119 | + restTemplate = new OAuth2RestTemplate(resource); |
| 120 | + } |
| 121 | + OAuth2AccessToken existingToken = restTemplate.getOAuth2ClientContext() |
| 122 | + .getAccessToken(); |
| 123 | + if (existingToken == null || !accessToken.equals(existingToken.getValue())) { |
| 124 | + DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken( |
| 125 | + accessToken); |
| 126 | + token.setTokenType(this.tokenType); |
| 127 | + restTemplate.getOAuth2ClientContext().setAccessToken(token); |
| 128 | + } |
| 129 | + return restTemplate.getForEntity(path, Map.class).getBody(); |
| 130 | + } |
| 131 | + catch (Exception ex) { |
| 132 | + this.logger.info("Could not fetch user details: " + ex.getClass() + ", " |
| 133 | + + ex.getMessage()); |
| 134 | + return Collections.<String, Object>singletonMap("error", |
| 135 | + "Could not fetch user details"); |
| 136 | + } |
| 137 | + } |
| 138 | +} |
0 commit comments