How can I use OAuth2RestTemplate in a scheduled task?

I have two resource servers: one that has an API for sending email notifications and one that runs scheduled tasks. When the scheduled task begins, I want to call the email service to notify users of the launch of their task. Both services use OAuth2 for authentication. The client’s credentials are set in the scheduled job service so that he can receive an access token by presenting the client credentials to him: Get token


Call service

For this, I use Spring Boot with Spring Security OAuth2. The Task service has an OAuth2RestTemplate to call the email service. When a scheduled task fires and tries to use the OAuth2RestTemplate, it tries to get the OAuth2ClientContext as a sesson-scoped bean. Obviously, he will not find it, since I do not execute in the request thread, I work in the background thread of the task. 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 

Since I use static credentials to authenticate the system for the system, I see no good reason to use scope data to process my access tokens. I would prefer to have a singleton OAuth2ClientContext bean, which any thread can use to create requests through OAuth2RestTemplate.

How to set it up?

+5
source share
1 answer

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

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

With the fact that in my @Configuration class, Spring connected it to my OAuth2RestTemplate, and my scheduled tasks were able to call the email service. For good measure, I added the @Primary annotation to make sure that this bean was preferred over everything that Spring created (not sure what is required).

+4
source

All Articles