2017-10-28 251 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