簡體   English   中英

如何在自定義過濾器中驗證Spring Security antmatcher

[英]How to validate spring security antmatcher in a custom filter

我定義了一個自定義過濾器,我在BasicAutenticationFilter之后添加了...

問題是,當我對微服務執行ping操作(在這種情況下,通過rancher的運行狀況檢查)時,它總是進入過濾器,並且認為應該執行該操作是不是,因為如果我將ping放入antmatchers允許allow所有請求,我的過濾器中的代碼是這樣的:

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

    }
}

提供在線集成測試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM