【问题标题】:PermissionEvaluator targetDomainObject is always null when checking hasPermission检查 hasPermission 时 PermissionEvaluator targetDomainObject 始终为 null
【发布时间】:2018-06-30 14:23:10
【问题描述】:

我正在开发一个 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();
    }

}

现在我要做的是在用户更新笔记本电脑之前进行检查,以确保他正在更新他的笔记本电脑而不是其他人的笔记本电脑。

这是我的笔记本电脑存储库

@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;
}

现在重点是

  • 如何区分 POSTPUT 方法?
  • 如果我将@PreAuthorize 更改为仅将实体传递给hasPermission 方法进行测试,它总是以null 的形式通过

【问题讨论】:

    标签: spring-security spring-data-rest spring-el


    【解决方案1】:

    如指南中所述

    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);
    

    添加任何注释解决了空对象的问题,我可以区分 PUT 和 POST 检查目标的 id 是否为空

    【讨论】:

      猜你喜欢
      • 2017-10-11
      • 1970-01-01
      • 2020-08-03
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多