Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting based on HTTP header in RESTeasy

I am developing REST services with two types.

  • before login no session token will be passed to HTTP header.
  • after login session token will be passed in each request.

I dont want to include @HeaderParam in each and every REST method. I want to intercept it first and based on that I want to check the validity of session. Please let me know

  1. how I can intercept based on headers in RESTEasy
  2. How to avoid intercepting few methods

Thanks.

like image 449
jaks Avatar asked Jul 18 '12 19:07

jaks


People also ask

What is interceptor in REST API?

Ad. Jakarta Restful Web Services includes an Interceptor API that allows developers to intercept request and response processing. This allows addressing some advanced concepts like authentication, caching, and compressing without polluting application code.

What are Httprequest headers?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


1 Answers

I solved this problem using PreProcessInterceptor

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Securable {
  String header() default "session-token";
}

@Provider
@ServerInterceptor
public class ValidationInterceptor implements PreProcessInterceptor, AcceptedByMethod {

  @Context
  private HttpServletRequest servletRequest;

  @Override
  public boolean accept(Class clazz, Method method) {
    return method.isAnnotationPresent(Securable.class);
  }

  @Override
  public ServerResponse preProcess(HttpRequest httpRequest, ResourceMethod resourceMethod) throws Failure,
      WebApplicationException {

    Securable securable =  resourceMethod.getMethod().getAnnotation(Securable.class);
    String headerValue = servletRequest.getHeader(securable.header());

    if (headerValue == null){
      return (ServerResponse)Response.status(Status.BAD_REQUEST).entity("Invalid Session").build();
    }else{
      // Validatation logic goes here
    }

    return null;
  }
}

The annotation @Securable will be used on REST service which needs to be validated.

@Securable
@PUT
public Response updateUser(User user)
like image 65
jaks Avatar answered Sep 23 '22 05:09

jaks