在jax-rs resteasy拦截器中检索客户端IP地址

时间:2014-07-04 12:57:03

标签: java web-services rest jax-rs resteasy

我有一个REST Web服务API,我需要通过几个标准来保护它。这是我的拦截器的剥离示例:

    @Provider
    @ServerInterceptor
    public class MySecurityInterceptor implements ContainerRequestFilter {

        private static final ServerResponse ACCESS_FORBIDDEN = new ServerResponse( "Nobody can access this resource", 403, new Headers<Object>() );;

        private static final ServerResponse SERVER_ERROR = new ServerResponse( "INTERNAL SERVER ERROR", 500, new Headers<Object>() );;

        @Override
        public void filter( ContainerRequestContext requestContext ) throws IOException {
            ResourceMethodInvoker methodInvoker = (ResourceMethodInvoker)requestContext.getProperty( "org.jboss.resteasy.core.ResourceMethodInvoker" );
            Method method = methodInvoker.getMethod();

            if ( !method.getDeclaringClass().isAnnotationPresent( ApiKey.class ) ) {
                requestContext.abortWith( SERVER_ERROR );
                RuntimeException e = new RuntimeException("...");
                throw e;
            }

            if ( method.isAnnotationPresent( PermitAll.class ) ) { //Everyone can call method
                return;
            }

            // -- No one
            if ( method.isAnnotationPresent( DenyAll.class ) ) {
                requestContext.abortWith( ACCESS_FORBIDDEN );
                return;
            }

            //... And so on
        }
    }

如果是PermitAll,我需要添加IP-Check。如何在这个地方获得来电IP地址?

1 个答案:

答案 0 :(得分:0)

ContainerRequestContext类提供了丰富的API来获取特定于请求的信息,例如请求URI,标头,实体,cookie或请求范围的属性。但是,不幸的是,它不提供有关客户端IP地址的信息。

要做的就是在过滤器中注入HttpServletRequest

    @Context
    HttpServletRequest httpRequest;

然后使用ServletRequest#getRemoteAddr()提取客户端IP地址。