3

I write a class extends ContainerRequestFilter for permission check. How can I get the matched methods' annotation for permission check.

@javax.ws.rs.ext.Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext requestContext) throws IOException {
    // how can I get resources' methods' annotation here? 
    // from the resource below , I want to checkout whether the target matched method contains the @ReadPermission annotation
    }
}

@Path("/region")
public class Region {
   @POST
   @Path("/{region_id}")
   @Produces({MediaType.APPLICATION_JSON , MediaType.APPLICATION_XML})
   @ReadPermission
   public String getRegion() {
      return null;
   }
}
Lyons Huang
  • 108
  • 2
  • 9
  • 1
    the best solution is http://stackoverflow.com/questions/29198555/get-resource-class-annotation-values-inside-containerrequestfilter – Lyons Huang Jan 16 '17 at 10:02

1 Answers1

8

You can use the following code (Specific for CXF):

 public class AuthorizationRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext requestContext) throws IOException {

        Message message = JAXRSUtils.getCurrentMessage();
        OperationResourceInfo operation = message.getExchange().get(OperationResourceInfo.class);
        Method m = operation.getMethodToInvoke();
        boolean hasAnnotation =  m.getAnnotation(ReadPermission.class) != null;
    }
}

Or this one (generic for JAX-RS)

@Provider
public class AuthorizationRequestFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(final ContainerRequestContext requestContext) throws IOException {
        resourceInfo.getResourceMethod().getAnnotation(ReadPermission.class);
    }
}
pedrofb
  • 37,271
  • 5
  • 94
  • 142
  • It works in cxf framework. But It depends cxf library. When I change the jax-rs implements from cxf to another(eg:Jersey ). It will not work. Is there any solution only depends jax-rs lib? After all , It work for me now, Thanks a lot – Lyons Huang Jan 16 '17 at 09:55
  • 1
    Take a look to this answer: http://stackoverflow.com/a/20950845/6371459. It is for jersey, but use jax-rs standard. I have not tested it with CXF – pedrofb Jan 16 '17 at 10:03
  • 1
    This question got marked as a dup, but it's not. It's the only correct answer I've seen for how to do this with CXF specifically. Thank you for posting this. – a9120bb Jul 12 '21 at 17:47