我的解决方案基于 Mop So 的回答,但没有使用:
return tokenEndpoint.getAccessToken(principal, parameters);
我用了:
tokenEndpoint.postAccessToken(principal, parameters);
为什么?因为如果你使用tokenEndpoint.getAccessToken(principal, parameters)
endpoing 会抛出你 aHttpRequestMethodNotSupportedException
因为它没有被GET
方法调用。至少,这是发生在我身上的spring-security-oauth2-2.0.13.RELEASE
public OAuth2AccessToken getAccessToken() throws HttpRequestMethodNotSupportedException {
HashMap<String, String> parameters = new HashMap<>();
parameters.put("client_id", CLIENT_ID);
parameters.put("client_secret", CLIENT_SECRET);
parameters.put("grant_type", "client_credentials");
ClientDetails clientDetails = clientDetailsStore.get(CLIENT_ID);
// Create principal and auth token
User userPrincipal = new User(CLIENT_ID, CLIENT_SECRET, true, true, true, true, clientDetails.getAuthorities());
UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(userPrincipal, CLIENT_SECRET,
clientDetails.getAuthorities());
ResponseEntity<OAuth2AccessToken> accessToken = tokenEndpoint.postAccessToken(principal, parameters);
return accessToken.getBody();
}