微服务架构中的可审核实体

时间:2019-09-10 08:30:19

标签: java spring-boot microservices

我正在尝试在当前的微服务架构中实现抽象可审核实体。对于单个模块,它工作正常,但是我对如何在多个模块之间传递SecurityContext感到困惑。

  • 我已经尝试过将令牌作为标头从我的zuul服务(身份验证服务器)传输到其他核心模块,并且该值始终为null。
  • 我还尝试使用伪装客户端传递SecurityContext,但它对我也不起作用。

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

Audit Logging in Spring Microservices

Session Management in microservices

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


}
}

0 个答案:

没有答案