我有一个要求以编程方式添加授权(权限)约束(在此不是身份验证)。我有一个应用程序范围的 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,但如果答案与容器无关,那就更好了。