【问题标题】:Spring-boot Zuul: Passing user ID between microservicesSpring-boot Zuul:在微服务之间传递用户 ID
【发布时间】:2019-02-12 02:42:15
【问题描述】:

我有一个 Zuul 网关代理,我在其中检查从用户收到的令牌的授权。现在,当这个请求被传递给其他微服务以获取用户特定的数据时,用户信息需要从网关传递到微服务。

现在,我已经在请求标头中添加了用户 ID,并使用 API header 注释在相应的微服务控制器中获取它。

这是传递用户信息的正确方式吗?还有其他更好的方法吗?

【问题讨论】:

  • 另外,您可以通过将zuul.sensitive-headers= 添加到.properties 文件来将令牌中继到下游服务。然后,在每个单独的服务中,使用细粒度的授权。
  • 在网关上,我检查令牌并获取实际用户名。这样就不需要在所有微服务中检查授权。所以在网关上,我收到了,但在验证令牌后,我得到了相应的用户 ID 并将其传递给其他微服务。
  • @GaneshSatpute:如果您找到了将此用户名传递给其他正在运行的微服务的方法,请告诉我。我遵循相同的架构,在 zuul 网关方式进行身份验证,但需要在其他微服务中访问用户名(与 JWT 令牌一起传递给 zuul api)。
  • @GhostRider 我最终也是这样做的。但不确定这是否是正确的方法。

标签: spring-boot authorization netflix-zuul


【解决方案1】:

如果有人仍然面临这个问题,

在 Zuul Proxy 中将 header 添加到 RequestContext 中,如下所示:

userId = jwtTokenUtil.getUsernameFromToken(jwtToken);

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

然后在各自的微服务中编写自定义过滤器并提取如下值

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

}

【讨论】:

    猜你喜欢
    • 2017-08-29
    • 2018-08-21
    • 2019-02-13
    • 2019-01-27
    • 2019-10-01
    • 2021-02-02
    • 2020-08-15
    • 2016-02-28
    • 2019-07-09
    相关资源
    最近更新 更多