相关疑难解决方法(0)

使用@ControllerAdvice使简单的servlet过滤器工作

我有一个简单的过滤器,只是为了检查一个请求是否包含一个带有静态密钥的特殊标头 - 没有用户身份验证 - 只是为了保护端点.我的想法是抛出一个AccessForbiddenException如果密钥不匹配的密钥,然后将其映射到带有注释的类的响应@ControllerAdvice.但是我不能让它发挥作用.我@ExceptionHandler没被打电话.

ClientKeyFilter

import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Controller

import javax.servlet.*
import javax.servlet.http.HttpServletRequest

@Controller //I know that @Component might be here
public class ClientKeyFilter implements Filter {

  @Value('${CLIENT_KEY}')
  String clientKey

  public void init(FilterConfig filterConfig) {}

  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
    req = (HttpServletRequest) req
    def reqClientKey = req.getHeader('Client-Key')
    if (!clientKey.equals(reqClientKey)) {
      throw new AccessForbiddenException('Invalid API key')
    }
    chain.doFilter(req, res)
  }

  public void destroy() {}
}
Run Code Online (Sandbox Code Playgroud)

AccessForbiddenException

public class AccessForbiddenException …
Run Code Online (Sandbox Code Playgroud)

spring exception-handling filter spring-security spring-boot

11
推荐指数
2
解决办法
5986
查看次数