java Sping Boot ,Spring Security返回状态401,而不是404,因为“没有找到HTTP请求的Map”

ecbunoof  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(91)

我正在使用Sping Boot 和Spring Security进行项目。Spring Security使用每个请求的session id验证header。如果会话ID无效或已过期,则将返回错误代码401。会话ID在到达控制器之前进行验证。
现在,我面临一个问题,如果用户输入一个没有有效会话ID的无效URL,响应代码仍然是401,因为会话ID首先被验证。我的预期是,如果URL无效,将返回错误代码404(未找到HTTP请求的Map)。换句话说,我想在验证会话ID之前验证URL。
有没有办法这样做,因为头中的会话id在到达控制器之前在GenericFilterBean中进行了验证?
任何帮助都是感激不尽的。谢谢

webghufk

webghufk1#

您可以尝试在WebSecurityConfigurerAdapter类中配置访问设置。

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

因此,过滤器不会为任何不匹配“/secure/**”模式的请求返回HTTP 401。

iibxawm4

iibxawm42#

将此过滤器作为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;
  }
}
oknwwptz

oknwwptz3#

@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
@Slf4j
@WebFilter
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 {
    try{
        boolean flag = validateUrl(request, response);
        if(flag)
            filterChain.doFilter(request, response);
    }catch (Exception ex){
        log.error("URL Filter Chain Exception:", ex);
        //throw new UrlNotFoundException(request, response, getRequestUri(request), ex);
    }
  }
  private boolean validateUrl(HttpServletRequest request, HttpServletResponse response) throws NoHandlerFoundException, IOException {
    if (null == getHandler(request)) {
        Status errorStatus = this.getErrorStatus(HttpStatus.NOT_FOUND.toString(), "URL not found", null);
        PlatformResponse errorResponse = new PlatformResponse();
        errorResponse.setStatus(errorStatus);
        response.setStatus(HttpStatus.NOT_FOUND.value());
        response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
        return false;
        //throw new UrlNotFoundException(request, response, "test", null);
    }
    return true;
  }
  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;
  }
}

稍微修改一下答案。
适用于springBootVersion: 3

相关问题