簡體   English   中英

Spring Boot,Spring Security 返回狀態 401 而不是 404,用於“未找到 HTTP 請求的映射”

[英]Spring Boot, Spring Security returns a status 401 instead of 404 for "no mapping found for HTTP request"

我有一個使用 Spring Boot 和 Spring Security 的項目。 Spring Security 使用每個請求的會話 ID 驗證標頭。 如果 session id 無效或過期,將返回錯誤代碼 401。 會話 id 在它到達控制器之前被驗證。

現在,我面臨一個問題,如果用戶輸入一個沒有有效會話 ID 的無效 URL,響應代碼仍然是 401,因為會話 ID 首先被驗證。 我的期望是,如果 URL 無效,將返回錯誤代碼 404(未找到 HTTP 請求的映射)。 換句話說,我想在驗證會話 ID 之前驗證 URL。

有沒有辦法這樣做,因為標頭中的會話 ID 在到達控制器之前在 GenericFilterBean 中進行了驗證?

任何幫助表示贊賞。 謝謝你。

您可以嘗試在 WebSecurityConfigurerAdapter 類中配置訪問設置。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/secure/**").authenticated()
        .and()
        .authorizeRequests().anyRequest().permitAll();
}

因此,過濾器不會為任何與“/secure/**”模式不匹配的請求返回 HTTP 401。

將此過濾器作為 Spring Security 中的第一個過濾器:

public class NoHandlerFoundFilter extends OncePerRequestFilter {

  private final DispatcherServlet dispatcherServlet;

  public NoHandlerFoundFilter(DispatcherServlet dispatcherServlet) {
    this.dispatcherServlet = dispatcherServlet;
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (null == getHandler(request)) {
      throw new NoHandlerFoundException(request.getMethod(), getRequestUri(request),
          new ServletServerHttpRequest(request).getHeaders());
    }
    filterChain.doFilter(request, response);
  }

  private static String getRequestUri(HttpServletRequest request) {
    String uri = (String) request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
    if (uri == null) {
      uri = request.getRequestURI();
    }
    return uri;
  }

  protected HandlerExecutionChain getHandler(HttpServletRequest request) {
    if (dispatcherServlet.getHandlerMappings() != null) {
      for (HandlerMapping mapping : dispatcherServlet.getHandlerMappings()) {
        try {
          HandlerExecutionChain handler = mapping.getHandler(request);
          if (handler != null) {
            return handler;
          }
        } catch (Exception ex) {
          // Ignore
        }
      }
    }
    return null;
  }
}

暫無
暫無

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

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