【问题标题】:Spring Data Rest with Spring Security - find all by current userSpring Data Rest with Spring Security - 按当前用户查找所有内容
【发布时间】:2018-04-10 00:56:48
【问题描述】:

是否可以使用 Spring Data Rest 和 Spring Security 返回当前用户相关实体,使用 findAll() 方法而不在 GET 查询参数中指定此用户?

我唯一的解决方案是将用户作为参数传递,但也许这是从 SpringSecurityContext 获取他的另一种选择

public interface InvoiceRepository extends CrudRepository<Invoice, Long> {
@RestResource
@PreAuthorize("hasRole('ROLE_ADMIN') or user?.username == authentication.name")
List<Invoice> findAllByUser(@Param("user") User user);

【问题讨论】:

    标签: rest spring-boot spring-security spring-data-rest findall


    【解决方案1】:

    您可以使用SpEL EvaluationContext extension 使安全属性和表达式在@Query 注释中的SpEL 表达式中可用。这允许您仅获取与当前用户相关的那些业务对象:

    interface SecureBusinessObjectRepository extends Repository<BusinessObject, Long> {
    
        @Query("select o from BusinessObject o where o.owner.emailAddress like ?#{hasRole('ROLE_ADMIN') ? '%' : principal.emailAddress}")
        List<BusinessObject> findBusinessObjectsForCurrentUser();
    }
    

    更多详情请联系here

    【讨论】:

    • @Cepr0 不错的答案,但是在这里我们需要做额外的查询,而且我们没有使用 jpa 存储库的全部功能。有没有什么击球手的方式来添加原则。
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 2018-10-25
    • 2023-03-16
    • 1970-01-01
    • 2020-12-02
    • 2023-04-07
    • 2020-10-24
    • 2014-06-10
    相关资源
    最近更新 更多