Two repos for the same entity, one exported and one not

孤者浪人 提交于 2019-12-22 07:47:48

问题


Using Sring Data JPA, Spring Data REST 2.4.2, Spring Security and Spring Boot 1.3.1. I have an Account entity that I want to expose over REST for admin purposes:

@PreAuthorize("hasRole('ROLE_ADMIN')")  //exclusive admin access
public interface AccountRepository extends JpaRepository<Account, Long> {}

This works as expected and I can access the REST interface with a proper admin role.

Another requirement I have is to allow non-admin users to register and authenticate over HTTP. For that I've created a custom Controller that exposes register() and login() functionality over /register and /login resources. The issue is that when the registration/login internal logic interacts with the repo above, there is no user security context that can be attached, apart from an anonymous one.

To keep things simple I have created a second repo that is not exported and has no security requirements:

@RepositoryRestResource(exported = false)
public interface AccountRepositoryInternal extends JpaRepository<Account, Long> {}

This repo is then then injected in the said controller.

The issue is that I see inconsistent behaviour with the exported interface. In some runtime environments the interface is exported over REST and in others it is not. Is there a better strategy I could use?


回答1:


You can add @PreAuthorize at both class and method level, so if you need only some methods do be secured just:

  1. Use only one repo instead of two
  2. Extend Repository instead that JPARepository
  3. Copy and paste (literally, they are just placeholders) all the methods that you need from PagingAndSortingRepository.

  4. Add @PreAuthorize accordingly to your needs to specific methods, not to the class.

Copying and pasting methods among repositories interfaces is what the docs suggests (http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#repositories.definition-tuning) if you want to have a fine grained control, such as in you case.



来源:https://stackoverflow.com/questions/35520362/two-repos-for-the-same-entity-one-exported-and-one-not

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