Asp.Net MVC自定义授权不起作用

时间:2016-10-20 09:40:14

标签: asp.net asp.net-mvc asp.net-mvc-4 authorization custom-authentication

我正在从事MVC项目。我想使用自定义授权属性。首先,我在this blog post中使用了一个示例。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string RolesConfigKey { get; set; }

    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) return;
        var authorizedRoles = ConfigurationManager.AppSettings["RolesConfigKey"];

        Roles = string.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) base.OnAuthorization(filterContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) return;
    }
}

我在我的基本控制器中使用这个自定义主体。

public class CustomPrincipal : IPrincipal
{
    public CustomPrincipal(string userName) { this.Identity = new GenericIdentity(userName); }

    public bool IsInRole(string userRoles)
    {
        var result = true;
        var userRolesArr = userRoles.Split(',');
        foreach (var r in Roles)
        {
            if (userRolesArr.Contains(r)) continue;
            result = false;
            break;
        }
        return result;
    }

    public IIdentity Identity { get; }
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string[] Roles { get; set; }
} 

在我的routeconfig中,我的默认路由是/Account/Index,其中用户登录操作。这是帐户控制器索引操作。

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Index(AccountViewModel accountModel)
    {
        var returnUrl = string.Empty;

        if (!ModelState.IsValid) { return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo); }

        var account = _accountService.CheckUser(accountModel.UserName, accountModel.Password);
        if (account == null) return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo);

        var roles = account.Roles.Select(r => r.RoleName).ToArray();
        var principalModel = new CustomPrincipalModel
        {
            UserId = account.UserId,
            FirstName = "FirstName",
            LastName = "LastName",
            Roles = roles
        };

        var userData = JsonConvert.SerializeObject(principalModel);
        var ticket = new FormsAuthenticationTicket(1, account.UserId, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
        var encryptedTicket = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        Response.Cookies.Add(cookie);

        SetCulture(account.DefaultCulture);

        if (!Array.Exists(roles, role => role == "admin" || role == "user")) return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo);

        if (roles.Contains("admin")) { returnUrl = Url.Action("Index", "Admin"); }
        if (roles.Contains("user")) { returnUrl = Url.Action("Index", "Upload"); }

        return SuccessfulLoginResult(accountModel.UserName, returnUrl);
    } 

正如您所看到的,当用户处于管理员角色时,此操作会重定向用户/Admin/Index,否则为/Upload/Index。但在我登录后,用户具有用户角色并键入/Admin/Index,授权过滤器无效,用户可以访问管理页面。

虽然我已将此属性添加到UploadController和AdminController,但此错误正在发生。我该如何解决这个问题?

[CustomAuthorize(Roles = "user")]
public class UploadController : BaseController

[CustomAuthorize(Roles = "admin")]
public class AdminController : BaseController

2 个答案:

答案 0 :(得分:1)

您需要为用户添加声明,将此部分添加到您的方法中:

. . .    

var roles = account.Roles.Select(r => r.RoleName).ToArray();

ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountModel.UserName));

roles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

identity.AddClaim(new Claim(ClaimTypes.Name, userCode.ToString()));

. . . 

答案 1 :(得分:0)

Problem solved with these changes.

In my CustomAuthorizeAttribute changed this line

if (!filterContext.HttpContext.Request.IsAuthenticated) return;

to

if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

And removed lines that I read allowed roles from web config. So my attributes final version like below

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" })); 
    }
}

Then I added a controller named ErrorController and redirected to this page when user not in role.

With these changes I realized that I was unable to access my /Account/Index and added [AllowAnonymous] attribute to actions below.

    [AllowAnonymous]
    public ActionResult Index() { return View(); }

    [HttpPost, ValidateAntiForgeryToken, AllowAnonymous]
    public ActionResult Index(AccountViewModel accountModel)