gpt4 book ai didi

java - 如何在自定义过滤器中验证 spring security antmatcher

转载 作者:行者123 更新时间:2023-11-30 05:49:53 26 4
gpt4 key购买 nike

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

问题是,当我 ping 我的微服务时(在这种情况下通过 Rancher 的健康检查)它总是进入过滤器,并且做的事情是假设它不应该,我说它假设它不应该因为我把ping 到 antmatchers 以允许所有请求,我的过滤器中的代码是这样的:

@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(); 时它应该验证antmatchers并返回existingAuth为true,我知道我知道这对我来说是很神奇的,但是然后,我需要找到一个方法来验证请求并告诉spring security在antmatchers列表中..

最佳答案

您可以只使用过滤器进行健康检查。将其放置在FIRST位置

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

}
}

在线integration tests are available

关于java - 如何在自定义过滤器中验证 spring security antmatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com