2016-03-16 26 views
0

我有一個名爲Order的類,如下所示。使用Spring Security控制JSON數據

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

使用Spring安全性,我需要能夠控制從Spring Controller作爲響應返回的數據。例如,管理員可以查看訂單的所有數據,但客戶只能看到姓名和金額。如何才能篩選與Spring Security.So JSON數據,爲管理最終輸出應該是

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

,併爲客戶輸出應該是

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

有沒有辦法做到這一點

+0

怎麼樣https://stackoverflow.com/questions/28794145/spring-data-rest-security-based-projection –

+0

我想控制JSON數據,而不是數據庫查詢。我使用Hibernate Criteria來查詢數據庫。 – Raghavendra

回答

0

你可以用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); 
} 

你需要添加一個Evalua tionContextExtensionSupport bean。這使您可以使用Spring Security表達式在Spring數據查詢:

@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數據REST

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

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

或考慮直接在數據庫中使用Column Security

+0

嗨,請您介紹更多關於第二種方法即EvaluationContextExtensionSupport。 – Raghavendra

+0

@Raghavendra只是讓你把彈簧安全表達式放到彈簧數據查詢中 –

相關問題