Best way to distribute credentials between microservices using spring-session

We are using an architecture very similar to that described in this excellent spring.io tutorial . Our gateway handles authentication and sessions are stored in Redis using spring-session. The endpoints of our microservices are secured and used by spring-session as well.

In a microservice, I need to call the endpoint of another microservice. I get the url easily through the discovery client, but I need to provide credentials and I'm not sure about the best way to achieve this.

I am thinking about getting the cookie SESSION from the HttpRequest, store it in some thread local variables, or request the scope of the bean and use it in the RestTemplate to call the second microservice. I need this scoped bean request because the RestTemplate will be used in the service layer, i.e. not in the MVC controller, and I don't want to pollute my service layer methods with this session ID that I get from the cookie.

Is there a better way to approach this need? Is there any support in Spring Cloud for this?

Thanks a lot for your input

+3


source to share


1 answer


Currently, the simplest way to access Spring session id is using RequestContextHolder.getRequestAttributes().getId()

. Once you have access to this, you can write a custom ClientHttpRequestInterceptor

one to include the session id in requests:

public SpringSessionClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        boolean isMyService = ...;

        // very important not to send the session id to external services
        if(isMyService) {
            request.getHeaders().add("x-auth-token", RequestContextHolder.getRequestAttributes().getId());
        }
    }
}

      



Then, when creating the RestTemplate, be sure to add SpringSessionClientHttpRequestInterceptor

.

RestTemplate rest = new RestTemplate();
rest.getInterceptors().add(new SpringSessionClientHttpRequestInterceptor());

      

+2


source







All Articles