【问题标题】:Control JSON data with Spring Security使用 Spring Security 控制 JSON 数据
【发布时间】:2016-07-02 20:58:02
【问题描述】:

我有一个名为 Order 的类,如下所示。

    class Order{
    private int id;
    private String name;
    private String amount;
    //getters and setters
    }

使用 Spring 安全性,我需要能够控制从 Spring Controller 作为响应返回的数据。例如,管理员可以查看订单的所有数据,但客户只能看到名称和金额。如何使用 Spring Security 过滤 JSON 数据。所以,管理员的最终输出应该是

     [{id:1,name:order1,amount:100}, {id:2,name:order2,amount:200}] 

客户的输出应该是

    [{name:order1,amount:100}, {name:order2,amount:200}].

有什么办法吗

【问题讨论】:

标签: json spring-mvc spring-security


【解决方案1】:

您可以使用 Spring Data 和 Spring Security 来破解它:

public interface FooRepository extends CrudRepository<Foo, Long> {

    @Query(
            value = "select id, amount, case when ?#{hasRole('admin')} then name else null end as name from foo where id=?1",
            nativeQuery = true
    )
    Foo findOne(Long id);
}

您需要添加一个 EvaluationContextExtensionSupport bean。这使您可以在 Spring Data 查询中使用 Spring Security 表达式:

@Component
public class MyEvaluationContextExtensionSupport extends EvaluationContextExtensionSupport{

    @Override
    public String getExtensionId() {
        return "security";
    }

    @Override
    public SecurityExpressionRoot getRootObject() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return new SecurityExpressionRoot(authentication) {};

    }
}

或者你可以试试 Projections 和 Spring Data REST

//untested:
@Projection(name = "detailed", types = Foo.class)
public interface FooDetailProjection {

    @Value("?#{ hasRole('admin')? target.name: null}")
    public String getName();
}

或者考虑直接在您的数据库中使用Column Security

【讨论】:

  • 嗨,您能否详细解释一下第二种方法,即 EvaluationContextExtensionSupport 。
  • @Raghavendra 只允许您将 Spring 安全表达式放入 Spring 数据查询中
猜你喜欢
  • 2014-02-04
  • 2022-12-05
  • 2013-11-25
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
  • 2021-02-08
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多