【问题标题】:Java (Jersey 2 + Grizzly 2) JAX-RS custom resource annotations for endpoints?Java(Jersey 2 + Grizzly 2)端点的 JAX-RS 自定义资源注释?
【发布时间】:2017-05-13 05:23:34
【问题描述】:

我想用某种“角色”属性注释我的所有 JAX-RS 资源,访问控制过滤器将通过上下文读取该属性。这种 JAX-RS 资源的一个示例是 (psuedo)

@Path("foo")
public class FooResource {

    @GET
    @Context(roles = "admin,user")
    public Response foo() {
      return Response.noContent().build();
    }
}

因此,AccessControlFilter 将有权访问资源特定的“角色”值:

public class AccessControlFilter {
  @Override
  public void filter(ContainerRequestContext context) throws IOException {
    String accessToken = accessToken(context);
    String roles = context.getContext("roles");    

    // ... validate access Token against roles ...

  }

  @Nullable
  private static String accessToken(ContainerRequestContext context) {
    Map<String, Cookie> cookies = context.getCookies();
    Cookie accessTokenCookie = cookies.get("access_token");
    if (accessTokenCookie != null) {
      return accessTokenCookie.getValue();
    }
    return null;
  }
}

我一直在挖掘:

【问题讨论】:

    标签: java servlets jersey jax-rs grizzly


    【解决方案1】:

    只需将ResourceInfo 注入过滤器类。从那里你可以得到资源Method。然后只需使用一些反射来获取注释。

    @Context
    private ResourceInfo resourceInfo;
    
    @Override
    public void filter(...) {
        Method method = resourceInfo.getResourceMethod();
        MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
        if (anno != null) {
            String roles = anno.value();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-14
      • 2014-12-18
      • 2014-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      相关资源
      最近更新 更多