返回 HTTP 错误 401 代码 &跳过过滤器链 [英] Return HTTP Error 401 Code & Skip Filter Chains

查看:21
本文介绍了返回 HTTP 错误 401 代码 &跳过过滤器链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用自定义 Spring Security 过滤器,如果 HTTP 标头不包含特定的键值对,我想返回 HTTP 401 错误代码.

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.

示例:

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) 并跳过剩余的过滤器链

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

(2) 抛出异常,最终导致 Spring Security 向客户端抛出 401 错误.

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

如果 #1 是更好的选择,我如何在响应中调用 setStatus(401) 后跳过过滤器链?

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

或者,如果#2 是正确的方法,我应该抛出哪个异常?

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

推荐答案

来自 doFilter 方法的 API 文档,你可以:

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

  • 要么使用 FilterChain 对象 (chain.doFilter()) 调用链中的下一个实体,
  • 不将请求/响应对传递给过滤器链中的下一个实体以阻止请求处理
  • 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

因此设置响应状态代码并立即返回而不调用 chain.doFilter 是您想要在此处实现的最佳选择.

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

这篇关于返回 HTTP 错误 401 代码 &跳过过滤器链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆