1

I have a spring boot application that uses OAuth2 for authentication. We need to rate limit attempts to sign in, the endpoint is /oauth/token.

I have been unable to get a filter in front of this filter, but have not been able to.

I've tried registering filters before BasicAuthenticationFilter in the WebSecurityConfigurerAdapter.

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

I've also attempted to add this filter in the normal filter chains with order of Integer.MIN_VALUE where the security context has an order set via application.properties with the property security.filter-order=5.

None of these have worked.

Is there a "Spring" way to add api rate limiting? If it is via filters, is there a way to get a filter to be active before the BasicAuthenticationFilter or other security filters?

GreenKiwi
  • 1,025
  • 13
  • 28
  • Could you try `OncePerRequestFilter` https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/filter/OncePerRequestFilter.html – Ataur Rahman Munna Feb 04 '18 at 04:51
  • Your order is wrong, because it is to high (2147483640). The authorization server security configuration has order 0. So your configuration is not used. Instead of creating an additional configuration, you could change the authorization server security configuration. – dur Feb 05 '18 at 12:10
  • Using servlet filter should also work, see https://stackoverflow.com/questions/25957879/filter-order-in-spring-boot. – dur Feb 05 '18 at 12:20

1 Answers1

3

Create a new @Component class that implements Filter and give it an @Order of HIGHEST_PRECEDENCE. Sample below:

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

    }
}
Olantobi
  • 869
  • 1
  • 8
  • 16