免责声明:我是 Entity REST SDK 的作者。
我采用了不同的方法并创建了安全上下文,其中包含在查询任何内容之前应该应用的所有必要的 lambda 表达式。
public class DefaultSecurityContext : BaseSecurityContext {
public static DefaultSecurityContext Instance = new DefaultSecurityContext();
// UserID for currently logged in User
public static long UserID{
get{
return long.Parse( HttpContext.Current.User.Identity.Name );
}
}
public DefaultSecurityContext(){
}
protected override void OnCreate(){
// User can access his own Account only
var acc = CreateRules<Account>();
acc.SetRead( y => x=> x.AccountID == UserID ) ;
acc.SetWrite( y => x=> x.AccountID == UserID );
// User can only modify AccountName and EmailAddress fields
acc.SetProperties( SecurityRules.ReadWrite,
x => x.AccountName,
x => x.EmailAddress);
// User can read AccountType field
acc.SetProperties<Account>( SecurityRules.Read,
x => x.AccountType);
// User can access his own Orders only
var order = CreateRules<Order>();
order.SetRead( y => x => x.CustomerID == UserID );
// User can modify Order only if OrderStatus is not complete
order.SetWrite( y => x => x.CustomerID == UserID && x.OrderStatus != "Complete" );
// User can only modify OrderNotes and OrderStatus
order.SetProperties( SecurityRules.ReadWrite,
x => x.OrderNotes,
x => x.OrderStatus );
// User can not delete orders
order.SetDelete(order.NotSupportedRule);
}
}
如您所见,我们也可以过滤对属性的访问。
如果您的大部分重复代码被安全上下文替换,您可以根据不同的用户角色创建不同的安全上下文并仍然保持相同的控制器。
public class OrdersController : WebAtomsController <MyEntities> {
protected override BaseSecurityContext CreateSecurityContext(){
return DefaultSecurityContext.Instance;
}
public ActionResult SearchOrders(
string productName,
string orderBy = "OrderID DESC",
int start = 0,
int size = 10)
{
// Where method automatically applies
// filter based on current SecurityContext
var aq = Where<Order>();
if(!string.IsNullOrEmpty(productName)){
aq = aq.Where(
x=> x.OrderItems.Any(
y=> y.Product.ProductName.StartsWith(productName)));
}
// OrderBy accepts string as a parameter
aq = aq.OrderBy(orderBy);
return aq.Page(start,size).Select(
y=> new {
y.OrderID,
y.OrderDate,
y.OrderStatus,
});
}
}
更多详情,请访问
https://entityrestsdk.codeplex.com