2017-10-28 327 views
2

是否有可能使用Spring数据休息和Spring安全性返回当前用户相关的实体,使用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); 

回答

5

您可以使用SpEL EvaluationContext extension,使得在@Query注释规划环境地政司表达式中可用的安全性和表达式。这可以让你获得仅仅与当前用户的业务对象:

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

+0

它的工作原理,谢谢! – ShaggyBathDuck

+0

@ShaggyBathDuck不要忘记接受/ upvoted答案,帮助你... – Cepr0