每当调用GET或POST来创建或编辑文章页面时,我都想使用以下方法:
' userId = ID or username of the user logged in
' companyId = ID or name of the company for which the current blog is assigned
' blogId = ID or name of the blog for which the article is being written
' returnSuccessView = the view that will be returned if the user has access
' returnFailView = the view that will be returned if the user does not have access
return View(CheckUserAccess(userId, companyId, blogId, returnSuccessView, returnFailView))
有人能告诉我这个功能会是什么样子吗?我的结构是:
公司 - >博客 - >文章 - >评论
我想创建权限,因此只有属于某个公司且属于某个博客且具有某些权限的用户才能执行所请求的任务。
例如,我的用户模型将具有用户可以与之关联的公司的ICollection,并且他们可以拥有他们可以与之关联的ICollection。他们还可以拥有ICollection权限,例如超级用户,文章编写者,文章编辑器,主持人等。
我会为权限创建一个单独的模型,以便可以通过UI添加和删除它们。
该功能应检查所请求的公司,博客和权限是否与用户所关联的内容相匹配(在ICollection中)。
最好的方法是什么?谢谢。
答案 0 :(得分:2)
我建议您使用自定义[Authorize]
属性来处理此问题。我们来举个例子:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
// The user is not even authenticated => we can't get much further
return false;
}
// At this stage we know that there's an authneticated user
// let's see who he is by fecthing his username
string username = httpContext.User.Identity.Name;
RouteData rd = httpContext.Request.RequestContext.RouteData;
// Now, let's read the companyId and blogId parameters that he sent
// into the request and ensure that he is not cheating on us
string companyId = rd.Values["companyId"] as string;
string blogId = rd.Values["blogId"] as string;
if (string.IsNullOrEmpty(companyId) || string.IsNullOrEmpty(blogId))
{
// One of the required parameters were not supplied when the action was invoked
// => we can't get much further
return false;
}
return IsOwner(username, companyId, blogId);
}
private bool IsOwner(string username, string companyId, string blogId)
{
// TODO: you know what to do here:
// check with your data store or wherever you have stored this info
throw new NotImplementedException();
}
}
现在您可以使用此属性修饰控制器/操作:
[MyAuthorize]
public ActionResult Edit(string companyId, string blogId)
{
// if we got that far it means that the user is authorized to edit this blog post
// and we could allow him to see the edit view
EditViewModel model = ...
return View(model);
}
当然为了确保用户不会在POST操作上欺骗你,你也可以用这个属性来装饰它:
[MyAuthorize]
[HttpPost]
public ActionResult Edit(EditViewModel model)
{
// if we got that far it means that the user is authorized to edit this blog post
// and we could go ahead and perform the necessary update
....
}