Cannot get JWT Token from Zuul Header in Spring Boot Microservice Module

一世执手 提交于 2019-12-11 17:05:18

问题


I have tried to send JWT Token in Zuul Header to another microservice module. Each Time request goes from zuul to another module but. I always get null header in another module. But I obtain token in zuul server from auth server but it never reaches to another module.

public class JwtTokenAuthenticationFilter extends OncePerRequestFilter {

private final JwtConfig jwtConfig;

public JwtTokenAuthenticationFilter(JwtConfig jwtConfig) {
    this.jwtConfig = jwtConfig;
}


private static final int FILTER_ORDER = 0;
private static final boolean SHOULD_FILTER = true;
private static final Logger logger = LoggerFactory.getLogger(AuthenticationFilter.class);


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

    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();

    String header = request1.getHeader(jwtConfig.getHeader());

    if (header == null || !header.startsWith(jwtConfig.getPrefix())) {
        chain.doFilter(request1, response);
        return;
    }

    /*   new token getting code*/
    String token = header.replace(jwtConfig.getPrefix(), "");


    try {
        Claims claims = Jwts.parser()
                .setSigningKey(jwtConfig.getSecret().getBytes())
                .parseClaimsJws(token)
                .getBody();

        String username = claims.getSubject();

        System.out.println(username);

        if (username != null) {
            @SuppressWarnings("unchecked")
            List<String> authorities = (List<String>) claims.get("authorities");
            UsernamePasswordAuthenticationToken auth =
                    new UsernamePasswordAuthenticationToken(
                            username,
                            null, authorities.stream().map(
                            SimpleGrantedAuthority::new
                    ).collect(Collectors.toList()));

            SecurityContextHolder.getContext().setAuthentication(auth);

        }
    } catch (Exception e) {
        SecurityContextHolder.clearContext();
    }


    System.out.println(String.format("%s request to %s", request1.getMethod(), request1.getRequestURL().toString()));
    /*   return null;*/

    request1.setAttribute("header",token);

    chain.doFilter(request1, response);


}

}

回答1:


In your application.properties of zuul you should add zuul.sensitiveHeaders=Cookie,Set-Cookie



来源:https://stackoverflow.com/questions/57864651/cannot-get-jwt-token-from-zuul-header-in-spring-boot-microservice-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!