如何限制角色对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; ... } 

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

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

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

真棒。 所以现在我们可以访问包含 superSecretValue字段的Person实体,如下所示:

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

我的问题是我们如何确保这一预测 ? 我们如何配置这样的东西,以便任何人都可以在没有 superSecretValue字段的情况下检索Person实体……但只有具有特定角色的人(例如, ROLE_ADMIN )才能使用投影来检索隐藏字段?

我发现了使用@PreAuthorize@Secured注释来保护Spring Data JPA存储库CRUD方法(例如save()delete() )的无尽例子……但是没有关于如何限制使用Spring Data REST投影的示例。

您可以使用带有条件SpEL表达式的@Value来重载投影中的属性 – 就像在此已经回答了类似的问题一样 。

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

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

另见:spring-data-rest DATAREST-428对此主题的问题。

您可以尝试这个解决方案: https : //stackoverflow.com/a/35399030/679240

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