Search code examples
javaspringrestsecuritymicroservices

SessionId lost when I make a request between backend of microservices


I am trying to make request between microservices in order to retrieve a list of users with the same roles. For this, first I make a request between FrontEnd and Backend inside the microservice 1. Following, I call an endpoint in the microservice 2 from Microservice 1 backend, but the session Id is lost in it, and I can retrieve the context. I am using spring security and Redis for the session Control. Manually, I retrieve the session Id from the microservice 1 and I add it as an attribute of the header of the second call, to the microservice 2. But it does not work.

String sessionID= RequestContextHolder.currentRequestAttributes().getSessionId();
RestTemplate rest = new RestTemplate();
HttpHeaders headers= new HttpHeaders();            
headers.set("Session",sessionID);
HttpEntity<ResponseData> entity = new HttpEntity<ResponseData>(headers);
ResponseEntity<ResponseData> responseEntity =rest.exchange(targetApi,  HttpMethod.GET, entity,ResponseData.class);

enter image description here


Solution

  • Finally, I resolved the problem adding an interceptor as a component:

    @Component
    public class SpringSessionClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    
        request.getHeaders().add("Cookie", "SESSION=" + sessionId);
        return execution.execute(request, body);
    }
    

    }

    And I created a @Bean to configure the rest template:

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate rest = new RestTemplate();
        ClientHttpRequestInterceptor interceptor= new SpringSessionClientHttpRequestInterceptor();
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(interceptor);
        rest.setInterceptors(interceptors);  
        return rest;
    }