简体   繁体   中英

Spring boot REST api implementing custom filter

I'm trying to apply a custom filter to my endpoints in a spring boot application, however I cant change the status of my response, it returns 200 even though I manually change it to 401.

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

  }

}

Any suggestions as to what might cause this problem?

You can throw an exception and handle it to return the 401.

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

Check here how to handle an exception:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM