【问题标题】:How do I add a rate limit filter before Oauth2 filters in Spring Boot如何在 Spring Boot 中的 Oauth2 过滤器之前添加速率限制过滤器
【发布时间】:2018-07-14 04:24:08
【问题描述】:

我有一个使用 OAuth2 进行身份验证的 Spring Boot 应用程序。我们需要对登录尝试进行速率限制,端点是/oauth/token

我一直无法在这个过滤器前面得到一个过滤器,但一直没能。

我尝试在 WebSecurityConfigurerAdapter 中的 BasicAuthenticationFilter 之前注册过滤器。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(final HttpSecurity http) throws Exception {
    http.addFilterBefore(filter, BasicAuthenticationFilter.class);
}

我还尝试将此过滤器添加到常规过滤器链中,顺序为Integer.MIN_VALUE,其中安全上下文的顺序通过application.properties 设置,属性为security.filter-order=5

这些都不起作用。

是否有“春天”的方式来添加 api 速率限制?如果是通过过滤器,有没有办法让过滤器在BasicAuthenticationFilter 或其他安全过滤器之前激活?

【问题讨论】:

标签: spring spring-mvc spring-boot spring-security


【解决方案1】:

创建一个新的@Component 类来实现Filter 并给它一个HIGHEST_PRECEDENCE 的@Order。示例如下:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class PreSecurityFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) {

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

        if (RATE_LIMIT_EXCEEDED) {
            // Return suitable response message
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } else {            
                // Only valid requests is allowed through the filter
                fc.doFilter(request, response);            
        }

    }
}

【讨论】:

  • 我们最终使用了@Order(Ordered.HIGHEST_PRECEDENCE),它正在工作。
猜你喜欢
  • 1970-01-01
  • 2017-11-22
  • 1970-01-01
  • 2014-09-04
  • 2013-11-18
  • 1970-01-01
  • 2017-02-21
相关资源
最近更新 更多