【问题标题】:Spring boot REST api implementing custom filterSpring Boot REST api实现自定义过滤器
【发布时间】:2017-03-17 12:31:33
【问题描述】:

我正在尝试在 Spring Boot 应用程序中将自定义过滤器应用于我的端点,但是我无法更改响应的状态,即使我手动将其更改为 401,它也会返回 200。

@Component
public class AuthFilter extends GenericFilterBean {

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = ((HttpServletRequest) req);
    HttpServletResponse response = ((HttpServletResponse) res);

    String URI = request.getRequestURI();
    String authHeader = request.getHeader("Authorization");

    boolean endPoint = URI.startsWith("/auth/") || URI.startsWith("/resource/") || URI.startsWith("/project/") || URI.startsWith("/skill/");

    if(endPoint) {
        if(authHeader == null || !authHeader.startsWith("Bearer")) {
            response.setStatus(401);
        }
    }
    chain.doFilter(request, response);

  }

}

关于可能导致此问题的任何建议?

【问题讨论】:

  • 试试:if(endPoint) { if (authHeader == ...) { response.setStatus(401); } else {chain.doFilter(request, response);}} else { chain.doFilter(request, response);}
  • 是的,这很有效,非常感谢!

标签: java spring filter request


【解决方案1】:

您可以抛出异常并处理它以返回 401。

if(endPoint) {
    if(authHeader == null || !authHeader.startsWith("Bearer")) {
        throw new ServletException("Invalid token."); // or your own exception to be handled
    }
}

在这里查看如何处理异常:

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    • 2019-08-06
    • 2019-01-04
    • 1970-01-01
    • 2017-03-17
    • 2022-12-11
    相关资源
    最近更新 更多