如何为 web.xml 中的安全注释配置我的实体过滤范围?

How do I configure my entity-filtering scope for security annotations in the web.xml?

阅读球衣文档:https://jersey.java.net/documentation/latest/entity-filtering.html 我能够通过将 SecurityEntityFilteringFeature 添加到我的 web.xml 以及其他已激活的功能来激活它。

所以我的 web.xml 的功能部分看起来像这样:

    ...
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>
            org.glassfish.jersey.server.gae.GaeFeature;
            org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
            org.glassfish.jersey.media.multipart.MultiPartFeature;
            org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
            org.glassfish.jersey.message.filtering.SecurityEntityFilteringFeature;
        </param-value>
    </init-param>
    ...

注释@PermitAll(什么都不改变)和@DenyAll(总是从 json 中删除实体)效果很好。

问题是:要使用注释 @RolesAllowed,我还需要按照文档中所述在实体过滤范围内注册角色

EntityFilteringFeature.ENTITY_FILTERING_SCOPE - "jersey.config.entityFiltering.scope"

Defines one or more annotations that should be used as entity-filtering scope when reading/writing an entity.

但我只能通过我的 web.xml 配置它,我无处可做以下操作:

new ResourceConfig()
// Set entity-filtering scope via configuration.
.property(EntityFilteringFeature.ENTITY_FILTERING_SCOPE, new Annotation[] {SecurityAnnotations.rolesAllowed("manager")})
// Register the SecurityEntityFilteringFeature.
.register(SecurityEntityFilteringFeature.class)
// Further configuration of ResourceConfig.
.register( ... );

猜对了吗?

您可以一起使用ResourceConfig 和web.xml。它不是 "either one or the other"。例如

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>org.foo.JerseyConfig</param-value>
    </init-param>
</servlet>

package org.foo;

public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        register(...);
        property(...);
    }
}

web.xml 和 ResourceConfig registrations/configuration/properties 等都将被使用。您可以看到一些其他部署选项,here

如果你真的必须远离ResourceConfig(不知道为什么会是这样的问题),你总是可以创建一个Feature .

@Provider
public class MyFilteringFeature implements Feature {

    @Override
    public boolean configure(FeatureContext context) {
        context.property(...);
        context.register(...);
        return true;
    }
}

然后只需注册该功能(除非您正在扫描包,否则应该使用 @Provider 注释将其拾取)。