• 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错误
  • 相关阅读:
    TCP流量控制
    TCP可靠传输的实现
    springbean补充:关于bean的属性
    mybatis分页插件,自动生成代码插件
    mybatis拦截器,分页插件
    mybatis注解开发
    mybatis缓存
    mybatis调用存储过程
    Oracle学习笔记12:oracle优化
    Oracle学习笔记11:触发器
  • 原文地址:https://www.cnblogs.com/luguojun/p/16132788.html
Copyright © 2020-2023  润新知