问题
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:
- Use only one repo instead of two
- Extend
Repository
instead thatJPARepository
Copy and paste (literally, they are just placeholders) all the methods that you need from
PagingAndSortingRepository
.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