<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
application.yml
security:
oauth2:
client:
client-id: client-id
client-secret: client-secret
grant-type: client_credentials
access-token-uri: ${oauth2-host}/oauth/token
@ConfigurationProperties(prefix = "security.oauth2.client")
@Bean
public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
return details;
}
@Bean({"clientCredentailsOAuth2RestTemplate "})
public OAuth2RestTemplate clientCredentailsOAuth2RestTemplate(ClientCredentialsResourceDetails clientCredentialsResourceDetails) {
return new OAuth2RestTemplate(clientCredentialsResourceDetails, new DefaultOAuth2ClientContext());
}
// 获取token
clientCredentailsOAuth2RestTemplate.getAccessToken()
// 调用资源API,会自动附带token
clientCredentailsOAuth2RestTemplate.getForObject(url,...)