如何在计划任务中使用 OAuth2RestTemplate? [英] How can I use an OAuth2RestTemplate in a scheduled task?

查看:60
本文介绍了如何在计划任务中使用 OAuth2RestTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两台资源服务器:一台具有用于发送电子邮件通知的 API,另一台运行计划任务.当计划任务开始时,我想调用电子邮件服务以通知用户他们的任务正在启动.这两种服务都使用 OAuth2 进行身份验证.计划任务服务设置了客户端凭据,以便它可以通过提供其客户端凭据来获取访问令牌:

I have two resource servers: one that has an API for emailing notifications and one that runs scheduled tasks. When a scheduled task starts, I want to call out to the email service to notify users that their task is starting. Both services use OAuth2 for authentication. The scheduled task service has client credentials set up so that it can get an access token by presenting it's client credentials:

为了实现这一点,我将 Spring Boot 与 Spring Security OAuth2 结合使用.任务服务有一个 OAuth2RestTemplate 来调用电子邮件服务.当计划任务启动并尝试使用 OAuth2RestTemplate 时,它​​会尝试将 OAuth2ClientContext 作为 sesson 范围的 bean.显然,它不会找到一个,因为我不是在请求线程中执行,而是在后台任务线程中操作.我收到此异常:

To accomplish this, I'm using Spring Boot with Spring Security OAuth2. The Task service has an OAuth2RestTemplate to make the call out to the Email service. When the scheduled task fires up and tries to use the OAuth2RestTemplate, it tries to get the OAuth2ClientContext as a sesson-scoped bean. Obviously, it's not going to find one since I'm not executing within a request thread, I'm operating in a background task thread. I get this exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
  'scopedTarget.oauth2ClientContext': Scope 'session' is not active for the current thread; 
  consider defining a scoped proxy for this bean if you intend to refer to it 
  from a singleton

由于我使用静态客户端凭据进行系统到系统身份验证,因此我认为没有充分理由使用会话范围的数据来处理我的访问令牌.我更喜欢有一个单例 OAuth2ClientContext bean,任何线程都可以使用它通过 OAuth2RestTemplate 发出请求.

Since I'm using static client credentials for system-to-system authentication, I don't see a good reason to use session-scoped data to handle my access tokens. I would prefer to have a singleton OAuth2ClientContext bean that any thread can use to make requests through an OAuth2RestTemplate.

我该如何配置?

推荐答案

结果非常简单.我想要一个单例 bean,所以我创建了一个单例 bean:

It turned out to be pretty simple. I wanted a singleton bean, so I created a singleton bean:

@Primary
@Bean
public OAuth2ClientContext singletonClientContext() {
    return new DefaultOAuth2ClientContext();
}

在我的@Configuration 类中,Spring 将它连接到我的 OAuth2RestTemplate 并且我的计划任务能够调用电子邮件服务.为了更好地衡量,我添加了 @Primary 注释以确保此 bean 优于 Spring Boot 创建的任何内容(不确定是否需要).

With that in my @Configuration class, Spring wired it in to my OAuth2RestTemplate and my scheduled tasks were able to call out the Email service. For good measure, I added the @Primary annotation to make sure this bean was preferred over anything that Spring Boot created (not sure if that's required).

这篇关于如何在计划任务中使用 OAuth2RestTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆