Reputation: 1046
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?
Upvotes: 1
Views: 2574
Reputation: 879
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);
}
}
}
Upvotes: 3