Ale*_*tig 2 spring-mvc spring-security rate-limiting
我正在使用 Spring MVC 4.1 向一个安静的 web 服务添加速率限制。
我创建了一个@RateLimited
可以应用于控制器方法的注释。Spring AOP 方面会拦截对这些方法的调用,并在请求过多时抛出异常:
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RateLimitingAspect {
@Autowired
private RateLimitService rateLimitService;
@Before("execution(* com.example..*.*(.., javax.servlet.ServletRequest+, ..)) " +
"&& @annotation(com.example.RateLimited)")
public void wait(JoinPoint jp) throws Throwable {
ServletRequest request =
Arrays
.stream(jp.getArgs())
.filter(Objects::nonNull)
.filter(arg -> ServletRequest.class.isAssignableFrom(arg.getClass()))
.map(ServletRequest.class::cast)
.findFirst()
.get();
String ip = request.getRemoteAddr();
int secondsToWait = rateLimitService.secondsUntilNextAllowedAttempt(ip);
if (secondsToWait > 0) {
throw new TooManyRequestsException(secondsToWait);
}
}
Run Code Online (Sandbox Code Playgroud)
这一切都完美无缺,除非@RateLimited
控制器方法的参数标记为@Valid
,例如:
@RateLimited
@RequestMapping(method = RequestMethod.POST)
public HttpEntity<?> createAccount(
HttpServletRequest request,
@Valid @RequestBody CreateAccountRequestDto dto) {
...
}
Run Code Online (Sandbox Code Playgroud)
问题:如果验证失败,验证器抛出MethodArgumentNotValidException
,它由 an 处理@ExceptionHandler
,它向客户端返回错误响应,从不触发 my@Before
并因此绕过速率限制。
如何以优先于参数验证的方式拦截这样的 Web 请求?
我想过使用 Spring 拦截器或普通 servlet 过滤器,但它们是由简单的 url-patterns 映射的,我需要通过 GET/POST/PUT/etc 进行区分。
我最终放弃了寻找 AOP 解决方案的尝试,而是创建了一个 Spring Interceptor。拦截器preHandle
的所有请求并监视其处理程序为 的请求@RateLimited
。
@Component
public class RateLimitingInterceptor extends HandlerInterceptorAdapter {
@Autowired
private final RateLimitService rateLimitService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (HandlerMethod.class.isAssignableFrom(handler.getClass())) {
rateLimit(request, (HandlerMethod)handler);
}
return super.preHandle(request, response, handler);
}
private void rateLimit(HttpServletRequest request, HandlerMethod handlerMethod) throws TooManyRequestsException {
if (handlerMethod.getMethodAnnotation(RateLimited.class) != null) {
String ip = request.getRemoteAddr();
int secondsToWait = rateLimitService.secondsUntilNextAllowedInvocation(ip);
if (secondsToWait > 0) {
throw new TooManyRequestsException(secondsToWait);
} else {
rateLimitService.recordInvocation(ip);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2255 次 |
最近记录: |