4

I have a REST Webservice API which I need to secure by several criterias. Here is a stripped example of my interceptor:

    @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
        }
    }

In case of PermitAll I need to add an IP-Check. How can I obtain the caller IP adress at this place?

peez80
  • 1,583
  • 2
  • 15
  • 32
  • 1
    Inject the `HttpServletRequest` and obtain the IP-Address [like explained here](http://stackoverflow.com/questions/4678797). – lefloh Jul 05 '14 at 05:31

1 Answers1

3

The ContainerRequestContext class provides a rich API to get request-specific information, such as the request URI, headers, entity, cookies or request-scoped properties. But, unfortunatelly, it does not provide information about the client IP address.

The way to go is inject the HttpServletRequest in your filter:

@Context
HttpServletRequest httpRequest;

And then extract the client IP address using ServletRequest#getRemoteAddr().


Note: Refer to this answer for other types that can be injected with @Context.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359