如何通过角色限制对Spring Data REST投影的访问?

Ste*_*ins 9 java rest spring spring-data spring-data-rest

在使用Spring Data JPA和Spring Data REST的应用程序中,假设您有一个这样的实体类:

@Entity
public class Person {

   @Id @GeneratedValue
   private int id;

   private String name;

   @JsonIgnore
   private String superSecretValue;

   ...

}
Run Code Online (Sandbox Code Playgroud)

我们希望Spring Data REST公开所有这个实体的字段EXCEPT superSecretValue,因此我们用这个字段注释了该字段@JsonIgnore.

但是,在某些情况下,我们想要访问superSecretValue,因此我们创建一个投影,返回所有字段,包括:

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

   String getName();
   String getSuperSecretValue();

}
Run Code Online (Sandbox Code Playgroud)

真棒.所以现在我们可以访问包括如下字段的Person实体:superSecretValue

curl http://localhost:8080/persons?projection=withSecret
Run Code Online (Sandbox Code Playgroud)

我的问题是我们如何确保这一预测?我们该如何配置的东西,任何人都可以检索Person实体,而不superSecretValue领域......但只用了一定的作用(比如人ROLE_ADMIN)可以使用投影来检索隐藏字段?

我发现使用的例子不胜枚举@PreAuthorize@Secured注释,以确保春季数据JPA库CRUD方法(例如save(),delete())...但不知道如何限制一个Spring数据REST投影的应用实例.

aux*_*aux 2

您可以使用@Value条件 SpEL 表达式重载投影中的属性 - 正如已经回答的类似问题一样。

考虑其他替代方案(其他方案已经提到):

  1. 模型重构。按访问逻辑拆分实体(例如Person<-> Account
  2. 添加自定义端点以进行特殊逻辑和访问检查。例如,当前用户位于“/people/me”。
  3. 自定义标准端点。例如,为“/people”、“/people/{id}”添加自定义控制器,该控制器将Resource根据用户权限进行预处理并返回自定义类型(DTO)(例如返回PublicPersonPerson。然后,您可以编写自定义资源处理器来添加这些类型的自定义链接和自定义投影。

另请参阅: spring-data-rest DATAREST-428关于此主题的问题。