我们可以在JPA的@Entity方法上使用Spring Security的@PreAuthorize、@PostAuthorize、@PreFilter或@PostFilter吗?
我找到的唯一的建议/答案是6+的老帖子,通常说“使用服务层”,有时“控制器也可以有安全注释,但服务层更直接”。
没有人会谈论在@Entity上使用安全注释。
为了解释简单的用例:假设我们有3个用于Person、Group和Party的Spring的JpaRepositories
@Entity
class Person {
...
@ManyToOne
Group group;
@ManyToOne
Party party;
}
@Entity
class Group {
...
@OneToMany
List<Person> people;
@ManyToOne
Party party;
}
@Entity
class Party {
...
@OneToMany
List<Person> people;
@OneToMany
List<Group> groups;
}所以基本上-一个人可以属于一个组,同时也可以属于一个政党。一个小组也可以属于一个党,可以有很多人。一个政党由许多小组和许多独立的人组成(这些人可能在小组中,也可能不在小组中)。
为了简洁起见,省略了很多代码,比如mappedBy、id和getters/setters/adders/removers。
如果我可以保护实体方法,我可以这样做:
@Entity
class Party {
...
@PreAuthorize("hasRole('ROLE_ADMIN')")
List<People> getPeople() { return this.people; }
}
@Service
class PartyService {
@Autowired
PartyRepository repo;
List<People> getPeople(Long partyId) {
return repo.getById(partyId).getPeople(); // Should either return people or throw access exception.
}
}
@Service
class GroupService {
@Autowired
GroupRepository repo;
List<People> getPeopleInMyParty(Long groupId) {
return repo.getById(groupId).getParty().getPeople(); // Should either return people or throw access exception.
}
}如果我不能保证实体方法的安全,我只能通过服务来解决,比如:
@Entity
class Party {
...
// Not secured here
List<People> getPeople() { return this.people; }
}
@Service
class PartyService {
@Autowired
PartyRepository repo;
@PreAuthorize("hasRole('ROLE_ADMIN')")
List<People> getPeople(Long partyId) {
return repo.getById(partyId).getPeople(); // Should either return people or throw access exception.
}
}
@Service
class GroupService {
@Autowired
GroupRepository repo;
@Autowired
PartyService partyService;
List<People> getPeopleInMyParty(Long groupId) {
return partyService.getPeople(repo.getById(groupId).getParty().getId()); // Should either return people or throw access exception.
}
}这在我的更复杂的JPA数据模型(及其获取服务)中带来了复杂性,因为我们得到了越来越多的@Service和@Repository注入,代码变得难以维护。看看两个示例的GroupService之间的区别--如果你放大它,你会得到大量的ID和所有相关服务的注入,而不仅仅是@Entity方法调用。
那么,我可以在@Entity级别上实现它吗?如何启用它?
发布于 2019-12-08 08:25:56
这个问题/问题产生了另一个问题,对这个问题的回答也解决了这个问题。
基本上,我首先发现Spring Security支持开箱即用的AspectJ (在一个子项目中附带了@Aspect ),经过一些配置后,我成功地设置了它,有效地能够对我的@Entity类进行@Secure (和其他安全注释)。
https://stackoverflow.com/questions/59164201
复制相似问题