For example I\'ve the following method:
@GET
@Path(\"/get/current\")
public Response getCurrentInfo(@HeaderParam(\"Authorization\") String token){
If you are using JAX-RS 2.0, you can inject ResourceInfo into a ContainerRequestFilter
, then get the java.lang.reflect.Method
from the. From the Method
, you can get the annotation. For example
@Provider
@Priority(Priorities.AUTHENTICATION)
public class SecurityFilter implements ContainerRequestFilter {
@Context
private ResourceInfo resourceInfo;
// You can get the header from the `requestContext`
@Override
public void filter(ContainerRequestContext requestContext) {
Method resourceMethod = resourceInfo.getResourceMethod();
SecurityCheck annotation = resourceMethod.getAnnotation(SecurityCheck.class);
// get some value from annotation
if (notAllowedAccess) {
throw new WebApplicationException(403);
}
}
}
This (the ResourceInfo
) is only necessary though if you need to get some value from the annotation, like @SecurityCheck("SomeRoleAllowed")
.
If you don't need the value, and all you want is for any method annotated to be filtered, then you can either create a DynamicFeature
, where you bind each method to a filter. For example
@Provider
public class SecurityCheckDynamicFeature implements DynamicFeature {
@Override
public void configure(ResourceInfo info, FeatureContext context) {
Method method = info.getResourceMethod();
SecurityCheck annotation = method.getAnnotation(SecurityCheck.class);
if (annotation != null) {
context.register(SecurityFilter.class);
}
}
}
Or another way is to just use @NameBinding
on the custom annotation
@NameBinding
@Target(...)
@Retention
public @interface SecurityCheck {}
Then you need to annotate the SecurityFilter
class with the annotation also. Any method or class annotated will go through the filter.
Other Resources: