我可以向JAX-RS方法添加自定义注释以验证访问吗?

Ana*_*oly 5 java annotations jax-rs

例如,我有以下方法:

@GET
    @Path("/get/current")
    public Response getCurrentInfo(@HeaderParam("Authorization") String token){

        Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
        .setPrettyPrinting().create();          

        String email = SecurityProvider.decryptTokenAndGetEmail(token);

        if(DB.isAccessPermitted(email)){
            Info info = DB.getCurrentInfo();
            String json = gson.toJson(info);
            return Response.ok(json).build();
        }else{
           return Response.status(401).build();
        }

    }
Run Code Online (Sandbox Code Playgroud)

所以改为写入每个方法:

          if(DB.isAccessPermitted(email)){
                Info info = DB.getCurrentInfo();
                String json = gson.toJson(info);
                return Response.ok(json).build();
            }else{
               return Response.status(401).build();
            }
Run Code Online (Sandbox Code Playgroud)

我将创建例如@SecurityCheck注释,注释每个具有有限访问权限的方法,并仅在一个地方执行检查.是否可以通过注释实现并且可以提供MVCE?谢谢.

Pau*_*tha 9

如果你使用的是JAX-RS 2.0,你可以注入ResourceInfo一个ContainerRequestFilter,然后从中获取java.lang.reflect.Method.从中Method,您可以获得注释.例如

@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

ResourceInfo只有当你需要从注释中获取一些值时,才需要这个()@SecurityCheck("SomeRoleAllowed").

如果您不需要该值,并且您想要的任何方法都是针对任何注释要过滤的方法,那么您可以创建一个DynamicFeature,将每个方法绑定到过滤器.例如

@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者另一种方法是仅使用@NameBinding自定义注释

@NameBinding
@Target(...)
@Retention
public @interface SecurityCheck {}
Run Code Online (Sandbox Code Playgroud)

然后,您还需要使用注释来注释SecurityFilter类.注释的任何方法或类都将通过过滤器.

其他资源: