You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JAX-RS中默认限制所有API仅admin角色访问,少数API开放其他角色?

Jersey全局默认@RolesAllowed("admin")配置方案

你的需求完全可以实现,不用给每个API手动加@RolesAllowed("admin"),下面是具体的实现方案:

问题说明

你当前在AppConfig上添加的@RolesAllowed("admin")不会自动作用于所有资源类,因为ResourceConfig本身不是Jersey的资源端点,这个注解在这里无效。我们需要通过扩展Jersey的安全动态特性来实现全局默认权限控制。

实现步骤

  1. 自定义权限控制Feature
    继承Jersey自带的RolesAllowedDynamicFeature,重写配置逻辑,给没有标注任何安全注解的API默认添加admin角色权限:
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.container.FeatureContext;
import javax.ws.rs.RolesAllowed;
import javax.ws.rs.PermitAll;
import javax.ws.rs.DenyAll;
import java.lang.reflect.Method;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;
import org.glassfish.jersey.server.filter.RolesAllowedRequestFilter;

public class CustomRolesAllowedDynamicFeature extends RolesAllowedDynamicFeature {
    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        Method method = resourceInfo.getResourceMethod();
        // 检查当前方法是否已有安全注解
        if (method.isAnnotationPresent(RolesAllowed.class) 
            || method.isAnnotationPresent(PermitAll.class)
            || method.isAnnotationPresent(DenyAll.class)) {
            super.configure(resourceInfo, context);
            return;
        }
        // 检查资源类是否已有安全注解
        Class<?> resourceClass = resourceInfo.getResourceClass();
        if (resourceClass.isAnnotationPresent(RolesAllowed.class)
            || resourceClass.isAnnotationPresent(PermitAll.class)
            || resourceClass.isAnnotationPresent(DenyAll.class)) {
            super.configure(resourceInfo, context);
            return;
        }
        // 无注解时默认应用admin角色权限
        context.register(new RolesAllowedRequestFilter("admin"));
    }
}
  1. 更新AppConfig配置
    修改你的AppConfig,替换原有的RolesAllowedDynamicFeature为自定义实现,同时可以去掉AppConfig上无效的@RolesAllowed("admin")注解:
@ApplicationPath("/ui/v1.0")
public class AppConfig extends ResourceConfig {
    public AppConfig() {
        System.out.println("!!!!!! Insights v10 UI starts !!!!!....");
        packages("com.test.app.ws.v10.ui");
        register(SecurityFilter.class);
        register(AuthenticationExceptionMapper.class);
        register(CustomRolesAllowedDynamicFeature.class); // 注册自定义Feature
    }
}

使用方式

  • 所有未标注安全注解的API,默认仅允许admin角色访问;
  • 少数需要例外的API,直接标注@PermitAll(允许所有已认证用户访问)或者其他@RolesAllowed(比如@RolesAllowed("user"))即可覆盖默认规则。

内容的提问来源于stack exchange,提问作者khateeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 19:45:03