Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring-boot Zuul: Passing user ID between microservices

I have a Zuul Gateway proxy, where I check the authorization of token received from the user. Now, when this is request is passed on to other microservices to get the user-specific data, the user information needs to be passed from the gateway to the microservice.

Right now, I've added the user ID in the request header and I'm getting it at respective microservice's controller using API header annotation.

Is this the right way to pass the user information. Is there any other better way?

like image 929
Ganesh Satpute Avatar asked Sep 06 '18 19:09

Ganesh Satpute


1 Answers

In case if anyone still facing this issue,

In Zuul Proxy add the header to RequestContext as below:

userId = jwtTokenUtil.getUsernameFromToken(jwtToken);

RequestContext ctx = RequestContext.getCurrentContext();
ctx.addZuulRequestHeader("userId", userId);

And then in the respective microservices write a custom filter and extract the value as below

@Component
public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                HttpServletResponse response,
                                FilterChain filterChain)
                                throws ServletException, IOException {

        String userId = request.getHeaders("userId").nextElement();
    
        logger.info("userId: "+userId);
    
        filterChain.doFilter(request, response);
    }

}
like image 71
Pradyskumar Avatar answered Jan 02 '23 11:01

Pradyskumar