Spring-boot Zuul: Passing user ID between microservices
Asked Answered
C

1

6

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?

Crossbred answered 6/9, 2018 at 19:13 Comment(4)
Alternatively you can relay token to downstream services by adding zuul.sensitive-headers= to .properties file. Then, in each individual service, use fine grained authorization.Heimlich
On gateway, I check the token and get the actual username. That way authorization need not be checked at all the microservices. So on Gateway, I receive, but after validating token I get the corresponding user ID and pass that along to other microservices.Crossbred
@GaneshSatpute: could you please let me know if you have found a way to pass this username to other running micro services. I am following the same architecture where authentication is happening at zuul gate way but needs to access the username( passed along with JWT token to zuul api) in other micro services.Literality
@GhostRider I end up doing the same way. But not sure if it is the right way.Crossbred
C
1

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);
    }

}
Chinatown answered 22/1, 2021 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.