1

我有一个要求以编程方式添加授权(权限)约束(在此不是身份验证)。我有一个应用程序范围的 CDI 托管 bean,如下所示。

@Named
@ApplicationScoped
public class Bean {
    @Inject
    private Service service;
    private List<Entity>list;

    public Bean() {}

    @PostConstruct
    private void init() {
        initialize();
    }

    private void initialize() {
        // Initialize the list on application start up.
        // The service.getList() method in an EJB is authenticated anonymously
        // for the first time on application start up.
        list=service.getList();

        // Do something programmatically to enforce the authority ROLE_ADMIN afterwords.
    }

    // This method is only invoked by an admin (ROLE_ADMIN) as and when required.
    // The @PostConstruct method may however be invoked by an anonymous user on start up.
    public void action() {
        initialize();
    }
}

是否可以在装饰有装饰的方法完成之前以编程方式强制执行权限/角色,@PostConstruct以便在装饰有装饰的方法完成其工作后service.getList(),只有具有所述ROLE_ADMIN权限的用户才能调用 EJB 方法@PostConstruct

换句话说,它的行为完全如下所示 - 一旦@PostConstruct完成它的工作?

@Stateless
@DeclareRoles(value = {"ROLE_ADMIN", "ROLE_USER"})
@RolesAllowed(value = {"ROLE_ADMIN"})
public class Skeleton implements Service {

    @Override
    public List<Entity> getList() {
        return entityManager.createQuery("SELECT e FROM Entity e").getResultList();
    }
}

我目前正在使用 GlassFish Server 4.1,但如果答案与容器无关,那就更好了。

4

1 回答 1

0

我不确定是否会起作用,但您可以尝试以下方法。创建一个接收 SessionContext 的 EJB Bean,然后使用方法 isCallerInRole(role)。

@Stateless
public class AuthorizationBean {
    @Resource
    private SessionContext sessionContext;

    public Boolean isCallerInRole(String role){
     return this.sessionContext.isCallerInRole(role);
    }
}

在你的类中注入这个bean,然后检查角色。这里的问题是它的类(ApplicationScoped)的范围,因为这不确定它是否会起作用。

于 2015-03-08T06:23:47.470 回答