【问题标题】:retrieving client IP address in jax-rs resteasy interceptor在 jax-rs resteasy 拦截器中检索客户端 IP 地址
【发布时间】:2014-07-04 12:57:03
【问题描述】:

我有一个 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地址?

【问题讨论】:

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


【解决方案1】:

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

要走的路是在你的过滤器中注入HttpServletRequest

@Context
HttpServletRequest httpRequest;

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


注意:其他可以用@Context注入的类型请参考this answer

【讨论】:

    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2019-09-25
    • 2011-09-09
    • 2017-05-05
    • 1970-01-01
    • 2018-08-21
    • 2016-01-10
    • 2019-04-19
    相关资源
    最近更新 更多