gpt4 book ai didi

breeze - 防止恶意数据更改的策略

转载 作者:行者123 更新时间:2023-12-01 11:48:46 25 4
gpt4 key购买 nike

寻找防止恶意数据更改的想法:用户 A 操纵(编辑或删除)属于用户 B 的数据。由于我们是在客户端创建实体,因此我们需要将它们(或至少其中一些)分配给经过身份验证的用户。

例如:

var newItem = ds.createNewItem();
newItem.OwnerId(22); //this is the problem that I see.
newItem.Name("New Item");
newItem.Description("I just changed your item!");
... //and so on
ds.saveChanges();

假设我们知道在我们的 API 上调用 SaveChanges 的用户的身份,我们如何针对该用户验证我们的实体(新的或修改的)?

首先想到的是子类化 EFContextProvider,重写 BeforeSaveEntity 并根据我们的用户身份检查实体 OwnerId 属性.例如:

if (entityInfo.Entity.GetType() == typeof(Item)
&& (entityInfo.EntityState == EntityState.Added
|| entityInfo.EntityState == EntityState.Modified)
&& ((Item)entityInfo.Entity).OwnerId != _currentUserId) {
return false
... //and so on

如果使用这种方法,在我们新的 EFContextProvider 类的构造函数中建立 _currentUserId 是否有意义?

解决这个问题的想法或更好的方法?

最佳答案

我认为您走在正确的轨道上。我自己也一直在思考这个问题,并且走了大致相同的道路。

假设您已经处理了身份验证并且有可用的 IPrincipal。您也有一个自定义的 IIdentity(称之为 AppIdentity),您可以在其中存储经过身份验证的用户的 UserId

Web Api 的基础 ApiController 类通过其 User 属性使环境 IPrincipal 可用。我们将在您的自定义 Breeze Web Api Controller 中利用它,它可能像这样开始:

[Authorize][JsonFormatter, ODataActionFilter]public class BreezeApiController : ApiController{    private readonly AppContextProvider _context;    public BreezeApiController() {        // pass 'User' IPrincipal to the context ctor        _context = new AppContextProvider(User);    }    ...    // one of the Query action methods    [HttpGet]    public IQueryable<Foo> Foos() {        return _context.Foos    }    ...

您的自定义 EFContextProvider 可能像这样开始:

public class AppContextProvider : EFContextProvider<AppDbContext>{    public AppContextProvider(IPrincipal user)    {        UserId = ((AppIdentity) user.Identity).UserId;    }    public int UserId { get; private set; }    ...

现在您可能想要防止 UserB 的实体被 UserA 看到。因此,您的自定义 EFContextProvider 可以相应地进行过滤,而不是允许每个 Foo 出门。

   public DbQuery Foos   {       get        {            // Here the 'Context' is your EF DbContext           return (DbQuery) Context.Foos               .Where(f => f.UserId == UserId);        }   }

回顾一下 Controller ,我们看到它的 Foos GET 操作方法忽略了过滤器……这是应该的。我们希望我们的 Controller 轻便,并将业务逻辑移至自定义 EFContextProvider 及其助手。

最后,高度简化的通用 BeforeSaveEntity 可能如下所示:

private bool BeforeSaveEntity(EntityInfo info){    var entity = info.Entity;    if (info.EntityState == EntityState.Added)    {        entity.UserId = UserId;        return true;    }    return UserId == entity.UserId || throwCannotSaveEntityForThisUser();}...private bool throwCannotSaveEntityForThisUser(){    throw new SecurityException("Unauthorized user");}

请注意,服务器上的自定义上下文提供程序负责设置添加的实体的 UserId。无论如何,我们不会相信客户会这样做。当然,它还负责验证修改和删除实体的 UserId

希望这对您有所帮助。 请记住,这只是草图。真正的交易会更加复杂,并被重构为助手。

关于breeze - 防止恶意数据更改的策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com