3

Is it possible to use Spring Data Rest and Spring Security to return current user related entities, using the findAll() method without specifying this user in the GET query parameter?

My only solution is to pass user as a parameter, but maybe it's another option to get him from 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);

1 Answers1

11

You can use SpEL EvaluationContext extension that makes security properties and expressions available in SpEL expressions in the @Query annotations. This allows you to get only those business objects that relate to the current user:

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

More details are here.

Cepr0
  • 28,144
  • 8
  • 75
  • 101
  • @Cepr0 nice answer, but here we need to do extra query, and we are not using full features of jpa repository. Is there any batter way to add principle. – Nitul Nov 24 '18 at 18:06