Return HTTP Error 401 Code & Skip Filter Chains

后端 未结 4 794
孤街浪徒
孤街浪徒 2020-12-09 15:49

Using a custom Spring Security filter, I\'d like to return an HTTP 401 error code if the HTTP Header doesn\'t contain a particular key-value pair.

Example:



        
相关标签:
4条回答
  • 2020-12-09 15:59

    Just do as they say in the upper answer. "so setting the response status code and returning immediately" This is just type:

    res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  
    return;
    
    0 讨论(0)
  • 2020-12-09 16:00

    From the API docs for the doFilter method, you can:

    • Either invoke the next entity in the chain using the FilterChain object (chain.doFilter()),
    • or not pass on the request/response pair to the next entity in the filter chain to block the request processing

    so setting the response status code and returning immediately without invoking chain.doFilter is the best option for what you want to achieve here.

    0 讨论(0)
  • 2020-12-09 16:05

    I suggest this solution below.

    public void doFilter(ServletRequest req, ServletResponse res,
                             FilterChain chain) throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest) req;
            final String val = request.getHeader(FOO_TOKEN)
    
            if (val == null || !val.equals("FOO")) {
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "The token is not valid.");
            } else {
                chain.doFilter(req, res);
            }
        }
    
    0 讨论(0)
  • 2020-12-09 16:11

    So you can use something like this.

    @Override
    public void doFilter() {
        if (whiteListOrigins.contains(incomeOrigin)) {
            httpResponse.setHeader("Access-Control-Allow-Origin", incomeOrigin);
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "Not Allowed to Access. Please try with valid Origin.");
        }
    }
    
    0 讨论(0)
提交回复
热议问题