1. 依赖
代码语言:javascript复制<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
2. 配置
application.yml
代码语言:javascript复制security:
oauth2:
client:
client-id: client-id
client-secret: client-secret
grant-type: client_credentials
access-token-uri: ${oauth2-host}/oauth/token
3. JAVA Config
代码语言:javascript复制@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());
}
4. 使用
代码语言:javascript复制// 获取token
clientCredentailsOAuth2RestTemplate.getAccessToken()
// 调用资源API,会自动附带token
clientCredentailsOAuth2RestTemplate.getForObject(url,...)
5. 注意
- 配置中如果没有security.oauth2.client.grant-type=client_credentials,初始化ClientCredentialsResourceDetails会无法获取到配置值
- 授权中心服务中,客户端授权类型不包含client_credentials,获取token时会出现HTTP 401错误