0

每当调用 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 中具有)相匹配。

做这样的事情的最好方法是什么?谢谢你。

4

1 回答 1

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
    ....
}
于 2012-07-27T15:34:56.420 回答