在Jersey 1.18.1中获取资源注释请求过滤器

时间:2015-06-05 18:45:09

标签: java rest annotations jersey dropwizard

我实现了一个用户授权模块,该模块将使用(新)注释应用于资源方法。
为了做到这一点,我创建了一个Jersey(请求)过滤器,我需要在其中获取注释以允许/禁止资源操作。

我使用Dropwizard 0.7.1和Jersey 1.18.1

资源类:

@Path("/v1/users/registration")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/users/registration")
public class UserRegistrationResource {
    @POST
    @AuthorizedFor(Realm.SOCIAL) // The custom annotation class
    public SessionModel register(
            @Valid
            @ApiParam(value = "New user to be registered", required = true)
            NewUser user) throws Exception {

        // Some logic
    ...
    }
}

过滤器类:

@Provider
public class AuthorizationFilter implements ContainerRequestFilter {

    @Context
    AbstractMethod method;

    @Override
    public ContainerRequest filter(ContainerRequest request) {

    // At this point, the method parameter is null :(

    Realm realm = null;
        User user = Context.get(Session.class).getUser();
        for (Annotation annotation : method.getAnnotations()) {
            if (AuthorizedFor.class == annotation.annotationType()) {
                realm = ((AuthorizedFor) annotation).value();
            }
        }
        if (realm != null) {
            for (Realm userRealm : user.getRole().getAllowedRealms()) {
                if (userRealm.equals(realm)) {
                    return request;
                }
            }
        }
        throw new ApiException(ResponseCode.UNAUTHORIZED);
    }
}

提供者类:

@Provider
public class AbstractMethodProvider extends AbstractHttpContextInjectable<AbstractMethod> implements InjectableProvider<Context, Parameter> {

    @Override
    public Injectable<AbstractMethod> getInjectable(ComponentContext ic, Context context, Parameter parameter) {
        if (parameter.getParameterType() == AbstractMethod.class) {
            return this;
        }
        return null;
    }

    @Override
    public ComponentScope getScope() {
        return ComponentScope.PerRequest;
    }

    @Override
    public AbstractMethod getValue(HttpContext context) {
        return context.getUriInfo().getMatchedMethod();
    }
}

过滤器和提供者初始化代码:

environment.jersey().getResourceConfig().getContainerRequestFilters().add(new AuthorizationFilter());
environment.jersey().register(new AbstractMethodProvider());

我还尝试在过滤器中注入HttpContext。它不是null,但getUriInfo()。getMatchedMethod()为null。
有没有更好的方法在Jersey请求过滤器中获取资源方法注释?

1 个答案:

答案 0 :(得分:2)

您可以实现ResourceFilterFactory来获取AbstractMethod。

public class AuthorizationFilterFactory implements ResourceFilterFactory {

    @Override
    public List<ResourceFilter> create(AbstractMethod abstractMethod) {
        return Arrays.asList(this.createAuthorizationFilter(abstractMethod));
    }

    private ResourceFilter createAuthorizationFilter(final AbstractMethod abstractMethod) {
        return new ResourceFilter() {
            @Override
            public ContainerRequestFilter getRequestFilter() {
                return new AuthorizationFilter(abstractMethod);
            }

            @Override
            public ContainerResponseFilter getResponseFilter() {
                return null;
            }
        };
    }
}

因此,您的AuthorizationFilter将如下所示:

@Provider
public class AuthorizationFilter implements ContainerRequestFilter {

    private final AbstractMethod method;

    public AuthorizationFilter(AbstractMethod method) {
        this.method = method;
    }

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        Realm realm = null;
        User user = Context.get(Session.class).getUser();
        for (Annotation annotation : method.getAnnotations()) {
            if (AuthorizedFor.class == annotation.annotationType()) {
                realm = ((AuthorizedFor) annotation).value();
            }
        }
        if (realm != null) {
            for (Realm userRealm : user.getRole().getAllowedRealms()) {
                if (userRealm.equals(realm)) {
                    return request;
                }
            }
        }
        throw new ApiException(ResponseCode.UNAUTHORIZED);
    }
}

注册您的工厂:

environment.jersey().getResourceConfig().getResourceFilterFactories().add(new AuthorizationFilterFactory());