【问题标题】:Spring service automatic calling Oauth2 protected servicesSpring服务自动调用Oauth2保护的服务
【发布时间】:2021-01-01 06:52:47
【问题描述】:

我有一个服务 A,它调用服务 B 来获取一些资源。当客户端使用访问令牌调用 A 并且 A 会将令牌中继到对 B 的请求时,它可以正常工作。

现在,我正在实现 redis 来缓存数据。当我收到来自 B 的消息更新时,我需要调用 B 来检索那些更新的资源。但是,A 现在没有访问令牌,我的请求也没有被授权。

有没有办法自动生成访问令牌?

感谢您的帮助。

【问题讨论】:

  • 请贴一些代码。没有它,很难知道您实际在做什么以及如何提供帮助。您如何收到更新的通知? A 是否以设定的时间间隔呼叫 B 以检查更新?还是你使用 Netty 推送数据?前端是否以设定的时间间隔调用后端 A,然后调用服务 B?还是其他设置?发布代码应该有助于回答这些问题,并更容易帮助您找到解决方案。

标签: spring redis oauth-2.0 access-token


【解决方案1】:

有一些工作要做,但不确定这是否是好的做法。

我为此创建了一个单独的 RestTemplate。

依赖:

        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-jwt</artifactId>
            <version>1.1.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
        </dependency>

启用:

@EnableOAuth2Client

application.yml:

security:
  oauth2:
    auto:
      clientId: <client id>
      clientSecret: <client key>
      grantType: password
      username: <username>
      password: <password>
      accessTokenUri: <URI>
      userAuthorizationUri: <URI>
      scope: openid profile email

配置:

    @Bean
    @ConfigurationProperties("security.oauth2.auto")
    protected ResourceOwnerPasswordResourceDetails autoOAuth2Details() {
        return new ResourceOwnerPasswordResourceDetails();
    }

    @LoadBalanced
    @Bean
    protected OAuth2RestTemplate autoRestTemplate(RestTemplateCustomizer customizer) {
        OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(autoOAuth2Details);
        customizer.customize(restTemplate);
        return restTemplate;
    }

使用这个模板,我的服务可以自己调用其他服务。

【讨论】:

    猜你喜欢
    • 2020-10-31
    • 2019-09-05
    • 2015-03-23
    • 2015-10-05
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2015-11-30
    相关资源
    最近更新 更多