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?
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.