我正在开发一个Spring Data Rest项目,并希望在创建或更新资源时检查用户权限
这是我的笔记本电脑课程
@Getter
@Setter
@Entity
public class Laptop {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String model;
@Column
private Long userId;
@PrePersist
void onCreate() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
AppUser appUser = (AppUser) authentication.getPrincipal();
userId = appUser.getId();
}
}
现在我想做的是在用户更新笔记本电脑之前检查,以确保他更新笔记本电脑而不是其他笔记本电脑。
这是我的LaptopRepository
@RepositoryRestResource(collectionResourceRel = "content")
public interface LaptopRepository extends CrudRepository<Laptop, Long> {
@Override
//@PreAuthorize("hasPermission(#entity, 'CREATE')")
@PreAuthorize("#entity.userId == principal.id")
<S extends Laptop> S save(S entity);
}
这是PermissionEvaluator的方法
@Override
public boolean hasPermission(Authentication authentication,
Object targetDomainObject, Object permission) {
return true;
}
现在重点是
- How do I distinguish between POST and PUT methods?
- If I change my @PreAuthorize to just pass the entity to the hasPermission method to just test, it always gets passes as null
答案 0 :(得分:0)
如指南中所述
import org.springframework.security.access.method.P;
...
@PreAuthorize("#c.name == authentication.name")
public void doSomething(@P("c") Contact contact);
import org.springframework.data.repository.query.Param;
...
@PreAuthorize("#n == authentication.name")
Contact findContactByName(@Param("n") String name);
添加任何注释解决了null对象的问题,我可以区分PUT和POST检查目标的id是否为null