RequestContextHolder is null when calling an external API using completable future

Viewed 168

I am using CompletableFuture which calls a helper method that makes a request to the external API and get the data. Before it makes a request, I am intercepting and performing the required OAuth2 authorization.

But for the request I am getting the "servlet request cannot be null" exception and during debug process I figured out that the attributes of RequestContextHolder Object is null and the reason for this is code is being executed on a separate thread. Is there any configuration that I can do so that whenever I use completable future and call to external api, it has the required attributes for the RequestContextHolder object.

#Snippet from the DefaultOAuth2AuthorizedClientManager class provided by the spring secur
    private static HttpServletRequest getHttpServletRequestOrDefault(Map<String, Object> attributes) {
        HttpServletRequest servletRequest = (HttpServletRequest) attributes.get(HttpServletRequest.class.getName());
        if (servletRequest == null) {
            RequestAttributes context = RequestContextHolder.getRequestAttributes();
            if (context instanceof ServletRequestAttributes) {
                servletRequest = ((ServletRequestAttributes) context).getRequest();
            }
        }
        return servletRequest;
    }

#Code snippet
     CompletableFuture<UserDto> userDetailsFuture = CompletableFuture
          .supplyAsync(() -> {
              //Helper method makes a request to the external API and get the data
            return clientHelper.getUserDetails(userId);
          });
0 Answers
Related