Two repositories for the same object, one exported and one not

Using Sring Data JPA, Spring Data REST 2.4.2, Spring Security and Spring Boot 1.3.1. I have an Account object that I want to expose for 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 the proper admin role.

Another requirement is to allow non-admin users to register and authenticate over HTTP. For this, I created a custom controller that exposes register () and login () functions on top of / register and / login resources. The problem is that when the internal registration / login logic interacts with the repo above, there is no user security context that can be attached other than anonymous.

To keep things simple, I 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 injected into the specified controller.

The problem is that I see inconsistent behavior with the exported interface. In some runtimes the interface is exported via REST, while in others it is not. Is there a better strategy I could use?

+4


source to share


1 answer


You can add @PreAuthorize

both at the class level and at the method level, so if you only need some methods, you can only protect:

  • Use only one repo instead of two
  • Expand Repository

    insteadJPARepository

  • Copy and paste (literally, they are just placeholders) all the methods you need from PagingAndSortingRepository

    .

  • Add @PreAuthorize

    as per your requirement to specific methods, not class.



Copying and pasting methods between repository interfaces is what the doc suggests ( http://docs.spring.io/spring-data/jpa/docs/1.9.2.RELEASE/reference/html/#repositories.definition-tuning ) if you want to have fine grained control like in your case.

+2


source







All Articles