Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two repos for the same entity, 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 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?

like image 949
florind Avatar asked Sep 26 '22 07:09

florind


1 Answers

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.

like image 116
Luca Abbati Avatar answered Oct 20 '22 00:10

Luca Abbati