How to restrict role access to a Spring Data REST project?

In an application using Spring Data JPA and Spring Data REST, let's say you have an entity class like this:

@Entity public class Person { @Id @GeneratedValue private int id; private String name; @JsonIgnore private String superSecretValue; ... } 

We want Spring Data REST to expose all of these EXCEPT entity fields for superSecretValue , and therefore we annotated this field using @JsonIgnore .

However, in some cases, we want to access superSecretValue , and therefore we create a projection that will return all fields, including this one:

 @Projection(name = "withSecret", types = {Person.class}) public interface PersonWithSecret { String getName(); String getSuperSecretValue(); } 

Tall. So now we can access the Person objects, including the superSecretValue field, like this:

 curl http://localhost:8080/persons?projection=withSecret 

My question is how can we provide this projection ? How can we set things up so that everyone can retrieve Person objects without a superSecretValue field ... but only people with a specific role (say ROLE_ADMIN ) can use a projection to retrieve a hidden field?

I have found endless examples of using @PreAuthorize or @Secured annotations to protect Spring JPA JPA data repository methods (e.g. save() , delete() ) ... but there are no examples on how to limit the use of Spring REST data projection.

+8
java spring rest spring-data spring-data-rest
source share
2 answers

You can overload properties in projections using @Value with @Value conditional expressions - as a similar question has already been answered .

Consider other alternatives (others already mentioned):

  • Refactoring a model. Split an object by access logic (e.g. PersonAccount )
  • Adding custom endpoints for custom logic and access control. For example, the current user in "/ people / me".
  • Configure standard endpoints. For example, add a user controller for "/ people", "/ people / {id}", which will process and return a custom Resource (DTO) type depending on the user's privileges (for example, return PublicPerson instead of Person ). You can then write your own resource processors to add custom links and custom predictions for these types.

See also: question on this from spring -data-rest DATAREST-428 .

+1
source share

You can try this solution: https://stackoverflow.com/a/312176/ ...

 @Projection(name = "detailed", types = User.class) public interface UserDetailProjection extends UserSimpleProjection{ @Value("#{@userService.checkAccess(target)? target.email : null}") public String getEmail(); } 
0
source share

All Articles