简体   繁体   English

在RESTeasy中基于HTTP标头进行拦截

[英]Intercepting based on HTTP header in RESTeasy

I am developing REST services with two types. 我正在开发两种类型的REST服务。

  • before login no session token will be passed to HTTP header. 在登录之前,没有会话令牌将传递给HTTP标头。
  • after login session token will be passed in each request. 登录后会话令牌将在每个请求中传递。

I dont want to include @HeaderParam in each and every REST method. 我不想在每个REST方法中包含@HeaderParam。 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 我如何根据RESTEasy中的标题进行拦截
  2. How to avoid intercepting few methods 如何避免拦截少数方法

Thanks. 谢谢。

I solved this problem using PreProcessInterceptor 我使用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注释将用于需要验证的REST服务。

@Securable
@PUT
public Response updateUser(User user)

There are two approaches 有两种方法

  1. Use JAX-RS interceptors - you have access to request object in the interceptor, so you can read headers 使用JAX-RS拦截器 - 您可以访问拦截器中的请求对象,因此您可以读取标头

  2. Use good old JavaServlet Filters - it is not a problem that you are using JAX-RS, you can filter REST requests as well. 使用好的旧JavaServlet过滤器 - 使用JAX-RS不是问题,您也可以过滤REST请求。 Similarly to interceptors, filters have access to request object, which has header information 与拦截器类似,过滤器可以访问具有头信息的请求对象

In both cases you can check if HttpSession exists ( request.getSession() method) and it has required attribute. 在这两种情况下,您都可以检查HttpSession是否存在( request.getSession()方法)并且它具有必需属性。

You can include/exclude requests filtered either in configuration or programatically in Java code, looking at request path. 您可以在配置中以编程方式或以编程方式在Java代码中包含/排除请求,查看请求路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM