使用application.properties中的值初始化过滤器

时间:2015-05-05 16:30:46

标签: java tomcat spring-boot servlet-filters jersey-2.0

我希望基于IP地址保护我的REST API(jersey2),但不会遇到Spring Security等问题。我只需将一些被授予完全访问权限的IP列入白名单。

为了实现这一点,我想到将IP放入application.properties并使用Filter强制执行限制。当使用嵌入式Jetty服务器时,这非常正常,但在Tomcat上部署应用程序时失败了。

我试图在Filter构造函数和init-method中读取属性(只有下面的代码片段中显示的构造函数示例)。然而,当访问存储IP的类字段(String ips)时,两者都会导致NullPointerException。另外使用Enviroment变量似乎也无济于事。

感谢任何帮助。谢谢!

@Component("RestAuthFilter")
public class RestAuthFilter implements Filter {

    private String ips;

    public RestAuthFilter() {
        try {
            final Properties p;
            final InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties");
            p = new Properties();
            p.load(input);
            ips = p.getProperty("whitelist.rest.ips");
        } catch(IOException e) {
            ips = "127.0.0.1";
        }
    }

    @Override
    public void init(final FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res,
                     final FilterChain chain) throws ServletException,     IOException {

        final List<String> allowedIPs = Arrays.asList(ips.split("[,]"));

        if(!allowedIPs.contains(req.getRemoteAddr())) {
            ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_FORBIDDEN, "Not allowed to use REST API!");
        } else {
            chain.doFilter(req, res);
       }
    }

    @Override
   public void destroy() {
   }

}

堆栈跟踪:

java.lang.NullPointerException: null
    at com.example.RestAuthFilter.doFilter(RestAuthFilter.java:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:113)
    at org.springframework.boot.context.web.ErrorPageFilter.access$000(ErrorPageFilter.java:59)
    at org.springframework.boot.context.web.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.boot.context.web.ErrorPageFilter.doFilter(ErrorPageFilter.java:106)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:1)

由于您使用的是Spring Boot并且您的设置非常标准,我会坚持使用PropertySource(通过@Value或Environment)从application.properties加载IP。话虽如此,并注意到您对使用环境的评论...

  

关于我所指的环境变量   org.springframework.core.env.Environment,我使用DI包括,   类似@Autowired Environment环境的类成员

你不能将它作为类成员注入并在构造函数中进行初始化,你将遇到范围问题 - 调用构造函数时不会设置Environment。您需要通过构造函数注入环境而不是类成员,例如:

@Component("RestAuthFilter")
public class RestAuthFilter implements Filter {

  private final List<String> restClientIps;

  @Autowired
  public RestAuthFilter(Environment env) {
    String restClientIpsProperty = env.getRequiredProperty("whitelist.rest.ips");
    restClientIps = // parse/split from restClientIpsProperty
  }
  ...
}