Java (Jersey 2 + Grizzly 2) JAX-RS custom resource annotations for endpoints?

360 views Asked by At

I'd like to annotate all of my JAX-RS Resources with some sort of "roles" attribute, that will be read through the context by an access control filter. An example of such a JAX-RS Resource is (psuedo):

@Path("foo")
public class FooResource {

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

Thus, the AccessControlFilter would have access to the resource-specific "roles" value:

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

I've been digging around:

1

There are 1 answers

0
Paul Samsotha On BEST ANSWER

Just inject ResourceInfo into the filter class. From there you can get the resource Method. Then just use some reflection to get the annotation.

@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();
    }
}