@PreAuthorize on JpaRepository

拥有回忆 提交于 2020-06-10 05:41:07

问题


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?


回答1:


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?




回答2:


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

}


来源:https://stackoverflow.com/questions/21568812/preauthorize-on-jparepository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!