我正在尝试用currentUser == entity.createdBy
过滤REST资源。因此,如果当前登录的用户名等于createdBy字段,则应返回它,否则返回。
但是我很难弄清楚该怎么做。
这是我的“启动”配置。我不得不实现自己的AuditorAwareRef
,其他@CreatedBy
却无法正常工作,即使它本来可以开箱即用:/-不知道那是什么。
@SpringBootApplication
@EnableJpaAuditing(auditorAwareRef="auditorProvider")
public class MyApplication {
@Bean
AuditorAware<String> auditorProvider() {
return new AuditorAwareImpl();
}
}
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
if (username == null)
return Optional.empty();
return Optional.of(authentication.getName());
}
}
我的实体
@Data
@Entity
@EntityListeners(AuditingEntityListener.class)
public class MyEntity {
@Id
@GeneratedValue
private Long id;
@CreatedBy
private String createdBy;
}
我的“控制器”
@RepositoryRestResource
public interface MyEntityRepository extends JpaRepository<Order, Long> {
// ... what do I type here?
}
我显然可以做到
Page<MyEntity> findByCreatedBy(@Param("createdBy") String createdBy, Pageable pageable);
但这并不理想,因为用户可以互相访问资源。我不要。
我尝试过:
@Query("select x from MyEntity x where x.createdBy = ?#{principal.name}")
Page<MyEntity> findMyEntities(Pageable pageable);
但是会出现此错误:
“ EL1008E:在类型'java.lang.Object []'的对象上找不到属性或字段'principal'-可能不是公共的或无效的吗?”
我也不喜欢使用@Query
注释来进行松散绑定。意思是如果不行,我不会得到编译错误。
有没有一种方法可以方便地由当前用户过滤实体?像这样:
Page<MyEntity> findByCreatedByEqualsCurrentUser(Pageable pageable);
或
Page<MyEntity> findByCreatedBy(@Principal("name") String createdBy, Pageable pageable);