Using Spring Security ACL with Spring Data REST
Asked Answered
M

1

18

I am trying to authorize apis exposed by Spring Data REST. So far I am able to do role-based authorization i.e:

@RepositoryRestResource(path = "book")
public interface BookRepository extends JpaRepository<Book, Long> {

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    <S extends Book> Book save(Book book);
}

Also in the same project i have a service layer with ACL mechanism, which is working.

I am unable to use PostFilter expression with Spring Data REST i.e:

@PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, admin)")
List<Book> findAll();

It would be of great help, if anyone using ACL with Spring Data REST.

Note: I am aware of below open issues:

https://github.com/spring-projects/spring-data-rest/issues/619 (formerly DATAREST-236)

https://github.com/spring-projects/spring-security/issues/2629 (formerly SEC-2409)

Mazurek answered 24/10, 2014 at 10:21 Comment(0)
M
45

using JpaRepository was shadowing List<Book> findAll() method. Then I used CrudRepository, and PostFilter got applied.

For more details, a sample project is available on GitHub: https://github.com/charybr/spring-data-rest-acl

ACL-based authorization is working for below entity exposed by Spring Data REST.

import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.security.access.method.P;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;

@RepositoryRestResource(path = "book")
public interface BookRepository extends CrudRepository<Book, Long> {

    @PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#book, 'write')")
    <S extends Book> Book save(@P("book") Book book);

    @Override
    @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, admin)")
    Iterable<Book> findAll();
}
Mazurek answered 25/10, 2014 at 16:53 Comment(3)
You sir deserve an upvote (even a year and a half later) for taking the time to come and post the answer to your own problem. Thank you !Hedwighedwiga
How to filter the results using @PostAuthorize within a findAll() function based on individual entity values inside the pageable array?Gregale
@Gregale for pageable @PostAuthorize is not a good idea. Please refer to docs.spring.io/spring-security/site/docs/4.0.x/reference/…Multinational

© 2022 - 2024 — McMap. All rights reserved.