Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

spring security - Return HTTP Error 401 Code & Skip Filter Chains

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:

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")) {
       // token is not valid, return an HTTP 401 error code
       ...
   }
   else {
    // token is good, let it proceed
    chain.doFilter(req, res);
   }

As I understand, I could do the following:

(1) ((HttpServletResponse) res).setStatus(401) and skip the remaining filter chain

OR

(2) throw an exception that, eventually, results in Spring Security throwing a 401 error to the client.

If #1 is the better option, how can I skip the filter chain after calling setStatus(401) on the response?

Or, if #2 is the right way to go, which exception should I throw?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...