自定义ASP.NET MVC角色提供程序不起作用

时间:2014-04-14 05:19:38

标签: c# asp.net-mvc asp.net-mvc-4 roleprovider

我创建了一个简单的角色提供者 LocalBankRoleProvider:

public override bool IsUserInRole(string username, string roleName)
    {
        var user = _repository.GetUser(username);
        var role = _repository.GetRole(roleName);

        if (!_repository.UserExists(user))
            return false;
        if (!_repository.RoleExists(role))
            return false;
        return user.Role.Name == role.Name;
    }


    public override string[] GetRolesForUser(string username)
    {
        var role = _repository.GetRoleForUser(username);
        if (!_repository.RoleExists(role))
            return new string[] { string.Empty };
        return new string[] { role.Name };
    }

LocalBankMembershipProvider:

 public override bool ValidateUser(string username, string password)
    {
        if (string.IsNullOrEmpty(password.Trim())
            || string.IsNullOrEmpty(username.Trim()))
            return false;
        var hash = LocalBankRepository.GetMd5Hash(password);
        return _repository.GetAllUsers().Any(user => (user.Name == username.Trim())
            && (user.Password == hash));

    }

HomeController中:

    [Authorize]
    public string Public()
    {
        return "public";
    }

    [Authorize(Roles = "Guests")]
    public string Users()
    {
        return "users";
    }

    [Authorize(Roles = "Administrators")]
    public string Admin()
    {
        return "Admin";
    }

的AccountController:

 [HttpGet]
    public ActionResult LogOn(string returnUrl)
    {
        return View();
    }


    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (_provider.ValidateUser(model.UserName, model.Password))
            {
                if (_roleProvider.IsUserInRole(model.UserName, "Administrators"))
                {
                    if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
                    //return RedirectToAction("Index", "Home");
                }
            }
            ModelState.AddModelError("Password", "The user name or password provided is incorrect.");
        }
        return View(model);
    }

的Global.asax:

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

WebConfig:

 <membership defaultProvider="LocalBankMembershipProvider">
  <providers>
    <clear />
    <add name="LocalBankMembershipProvider" type="WebApplication1.Abstract.LocalBankMembershipProvider" connectionStringName="UsersDbEntities" />
  </providers>
</membership>

<roleManager defaultProvider="LocalBankRoleProvider" enabled="true" cacheRolesInCookie="false">
  <providers>
    <clear />
    <add name="LocalBankRoleProvider" type="WebApplication1.Abstract.LocalBankRoleProvider" connectionStringName="UsersDbEntities" />
  </providers>
</roleManager>

以上所有功能都有效。

问题仍然存在:
我试图将用户重定向到管理员方法,但没有工作,并重定向到LoginForm
有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决问题的方法 问题是:

 public static string GetMd5Hash(string value)
    {
        var md5Hasher = MD5.Create();
        var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(value));
        var sBuilder = new StringBuilder();
        for (var i = 0; i < data.Length; i++)
        {
            sBuilder.Append(i.ToString("x2"));
        }
        return sBuilder.ToString();
    }

必须是:

public static string GetMd5Hash(string input)
    {
        if (String.IsNullOrWhiteSpace(input))
            return String.Empty;

        // step 1, calculate MD5 hash from input
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
        byte[] hash = md5.ComputeHash(inputBytes);

        // step 2, convert byte array to hex string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("x2"));
        }
        return sb.ToString();
    }