Вопрос

I am looking to implement role based security for my REST service. I am using spring-data-rest and have configured a JpaRepository as such:

@Repository
@RestResource(path = "changesets", rel = "changesets")
public interface ChangesetRepository extends JpaRepository<Changeset, Long> { }

I would like to attach a @PreAuthorize annotation to the inherited Page<T> findAll(Pageable pageable) method so that a GET requires a specific role.

Is there a way to do that? Do I need to provide a custom implementation or am I missing something obvious?

Это было полезно?

Решение

You can add your own parent class for all repositories (see how to do it in the documentation). Then just add all necessary annotations and your security restrictions will be applied for all child beans.

From the architecture point of view most of the time a Repository is not the right place to apply your security restrictions. Your service layer is much more appropriate place (because your security restrictions depend on your business actions and not on your data loading logic). Consider following example: you want to reuse the same Repository in many Services, and security rules are not the same (for these Services). What to do?

Другие советы

If you are using Spring Data REST your idea is reasonable. In your interface class just redefine the same method and add @PreAuthorize annotation to it. Code should be like this, though I didn't test it

@Repository
@RestResource(path = "changesets", rel = "changesets")
public interface ChangesetRepository extends JpaRepository<Changeset, Long> { 

@PreAuthorize("#pk == authentication.id") 
Page<Changeset> findAll(Pageable pageable);

}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top