spring cloud以客户端授权模式访问受oauth2保护的资源

1. 依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>

2. 配置

application.yml

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

@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. 使用

// 获取token
clientCredentailsOAuth2RestTemplate.getAccessToken()
// 调用资源API,会自动附带token
clientCredentailsOAuth2RestTemplate.getForObject(url,...)

5. 注意

  • 配置中如果没有security.oauth2.client.grant-type=client_credentials,初始化ClientCredentialsResourceDetails会无法获取到配置值
  • 授权中心服务中,客户端授权类型不包含client_credentials,获取token时会出现HTTP 401错误

posted on 2022-04-11 22:39  路过君  阅读(121)  评论(0编辑  收藏  举报

导航