Spring-Security-OAuth2调用微信API
class WeixinClientCredentialsAccessTokenProvider extends ClientCredentialsAccessTokenProvider {
public WeixinClientCredentialsAccessTokenProvider() {
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new MappingJackson2HttpMessageConverter());
this.setMessageConverters(converters);
this.setTokenRequestEnhancer(new RequestEnhancer() {
@Override
public void enhance(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource,
MultiValueMap<String, String> form, HttpHeaders headers) {
form.set("appid", resource.getClientId());
form.set("secret", resource.getClientSecret());
form.set("grant_type", "client_credential");
}
});
}
}
OAuth2ClientContext context = new DefaultOAuth2ClientContext();
ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
resource.setClientId("xxxxxxxxx");
resource.setClientSecret("xxxxxxxxxxxxxxx");
resource.setAccessTokenUri("https://api.weixin.qq.com/cgi-bin/token");
resource.setAuthenticationScheme(AuthenticationScheme.form);
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(resource, context);
restTemplate.setAccessTokenProvider(new WeixinClientCredentialsAccessTokenProvider());
restTemplate.setRetryBadAccessTokens(true);
ResponseEntity<Object> response = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/user/get", Object.class);
if (response.getStatusCode() == HttpStatus.OK) {
System.out.println(response.getBody());
}