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: 

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?
source share