I'm using OAuth2RestTemplate in my Spring boot application and work with some resource through it as it encapsulates all the authentication info, so i can just send the requests, not worrying about tokens and other auth stuff.
That all works fine until i send the requests in parallel.
Because of the OAuth2RestTemplate has a Session scope (which is local as it contains user's session-related info), when i'm trying to use it in multi-thread environment, i get the following 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; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
As I understand, this happens because these separate threads, where the code is being executed, are not wired with session.
The only solution i found for now is binding the session with new threads manually in code, but it i don't like it.
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
Stream.of(1, 2, 3).parallel().forEach(it -> {
RequestContextHolder.setRequestAttributes(requestAttributes);
//do something
RequestContextHolder.resetRequestAttributes();
});
RequestContextHolder.setRequestAttributes(requestAttributes);
There's a ticket on Spring Jira where similar issue were discussed but still i still hope that there's some solution related to OAuth2RestTemplate.
So i'm wondering if anyone meet this and how you resolved it.