所以,基本上这里你似乎担心某些用户可能会修改属于另一个用户的物品。好吧,这句话告诉我们你已经有了你的应用程序中的用户和项目,并且有一些角色与这些项目相关联。你有一个机制来识别这些用户。因此,您可能正在使用某种身份验证,例如内置的FormsAuthentication。所以现在问题就变成了:如何确保当前经过身份验证的用户不会修改属于其他用户的产品。
好的,所以你有属于用户的物品。我想这些信息存储在服务器的某个地方,大概是数据库或其他东西。我建议你的一种方法是编写一个自定义授权属性,该属性将检查请求的资源id
实际上是否属于当前经过身份验证的用户。
例如:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
// The user is not authenticated or authorized => no need to continue further
return false;
}
// At this stage we know that the user is authorized => we can fetch
// the username
string username = httpContext.User.Identity.Name;
// Now let's fetch the id of the resource he is trying to manipulate from the request
string id = httpContext.Request["id"];
// All that's left is to verify if the current user is the owner
// of the account
return IsOwnerOfItem(username, id);
}
private bool IsOwnerOfItem(string username, string id)
{
// TODO: query the backend to perform the necessary verifications
// about whether the user has permissions to work with the resource
// pointed by the id parameter
throw new NotImplementedException();
}
}
现在所有剩下的就是这个自定义属性来装饰你的AddProduct
控制器动作:
[MyAuthorize]
public ActionResult AddProduct(int id)
{
// if we get that far we know that the currently authenticated user
// is the owner of the resource pointed by the id parameter and we
// could proceed respectively
...
}
通过这种方法,你不需要使用任何会话或加密任何东西。加密已经以Forms Authentication cookie的形式嵌入ASP.NET框架中,该cookie以安全的方式保存当前认证的用户名。这个cookie不能被操纵 - >用户不能模仿另一个用户。因此,一旦您得到了关于当前用户的身份的保证,那么剩下的就是执行必要的授权,无论他是否可以访问请求的资源。