如何通过将存储在表中的用户ID与Asp.net MVC 5中的当前用户ID进行比较来创建自定义授权属性?

时间:2015-10-11 19:59:43

标签: c# asp.net-mvc-5 authorize-attribute

我需要根据用户ID控制对我的控制器的编辑方法的访问,即只有用户才能访问创建该特定数据的编辑方法。 用户ID存储在表EmpProfile UserID列中,并希望将当前登录的用户与存储的UserID进行比较,并在此基础上允许访问。 我的自定义授权属性代码是:

public class AuthorizeAuthorAttribute : AuthorizeAttribute
{        
    RecruitDB mydb = new RecruitDB();   // My Entity
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {
            return false;
        }
        string CurrentUser = httpContext.User.Identity.GetUserId().ToString(); // Current User ID(Converted to string)

        var userName = from m in mydb.EmpProfiles            //Calling method to get UserID from EmpProfile.UserID Column
                       where m.UserID == CurrentUser
                       select m.UserID;
        string my = userName.ToString();                    //Converting to string
        if (CurrentUser.Contains(my))                       //Comparing
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }       
}

控制器代码:

[AuthorizeAuthor]
    public ActionResult Edit(int? id)
    {
    }

但是通过应用授权,我总是被引导到登录页面。 此外,当用户与作者相同时。

1 个答案:

答案 0 :(得分:1)

回应你的评论:

  

通过向我的操作添加[Authorize(User="SomeUser")],只允许特定的硬编码用户输入。但是用户如何才能创建数据只能被授权。对于它,当前用户ID和数据创建者用户ID应该匹配。很多像站点用户仪表板只能由创建它的用户访问。 MVC是否提供此类授权?请建议

您注意到Authorize属性(与.NET中的所有属性一样)只能包含const参数,这是正确的。

为了灵活性,您不能在这种情况下使用属性,您必须实现自己的授权逻辑并执行来自控制器操作的调用,如下所示:

public ActionResult Edit(Int32? id) {
    // Repeat the below logic for each action you want access-control in, ensure it is also in your POST handlers too.
    if( !this.IsAuthorized() ) return this.Http401();
}

protected boolean IsAuthorized() {
    if( this.Request.User.Identity.Name == "someoneIDontLike" ) return false;
    return true;
}

protected ActionResult Http401(String message) {
    this.Response.StatusCode = 401;
    // This requires you to create your own custom HTTP 401 "Unauthorized" view file and viewmodel
    return this.View( new Http401ViewModel(message) );
}