提问者:小点点

如何在自定义筛选器中验证Spring安全蚁匹配器


我已经定义了一个自定义过滤器,我在 BasicAutenticationFilter 之后添加了...

问题是,当我ping我的微服务(在这种情况下通过牧场主的健康检查)时,它总是去过滤器,并且做一些事情是假设它不应该,我说它应该不应该,因为我将ping放入蚁匹配器以允许所有请求,我的过滤器中的代码是这样的:

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    logger.debug(this + "received authentication request from " + request.getRemoteHost() + " to " + request.getLocalName());

    if (request instanceof HttpServletRequest) {
        if (isAuthenticationRequired()) {
            authenticate(request,response);
        } else {
            logger.debug("session already contained valid Authentication - not checking again");
        }
    }
    chain.doFilter(request, response);
}   

private boolean isAuthenticationRequired() {
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if ((existingAuth == null) || !existingAuth.isAuthenticated()) {
        return true;
    }
    return false;
}  

我假设,当你SecurityContextHolder.getContext().getAuthentication();它应该验证蚂蚁匹配器并以 true 返回现有的身份验证,我知道我知道这很神奇,就像我一样思考,但是,我需要找到一个来验证请求并告诉 Spring Security 在蚁匹配器列表中。.


共1个答案

匿名用户

您可以只使用过滤器来进行运行状况检查。首先将其放置到位

public class HealthFilter extends OncePerRequestFilter {

    private String healthPath = "/healthcheck/**";
    private AntPathRequestMatcher matcher = new AntPathRequestMatcher(healthPath);

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

        if (matcher.matches(request)) { //evaluate health check
            //do anything you want over here.
            //including performing your health check
            response.getWriter().write("OK");
            response.setStatus(200);
        }
        else {
            //only execute the other filters if we're not doing a health check
            filterChain.doFilter(request, response);
        }

    }
}

在线集成测试可用