mvc 4无法自定义授权角色

时间:2012-11-20 09:26:36

标签: asp.net-mvc authorization

HomeController

 [Authorize(Roles = "Member")]
public ActionResult Contact()
{
    return View();
}

Global.asax中

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        //Construst the GeneralPrincipal and FormsIdentity objects
        var authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (null == authCookie)
        {
            //no authentication cokie present
            return;
        }
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        if (null == authTicket)
        {
            //could not decrypt cookie
            return;
        }
        //get the role
        var role = authTicket.UserData.Split(new[] { ',' });
        var id = new FormsIdentity(authTicket);
        Context.User = new GenericPrincipal(id, role);
    }

的AccountController

 [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && _userbll.ValidateUser(model.UserName, model.Password))
        {
            var ticket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, model.RememberMe ? DateTime.Now.AddDays(14) : DateTime.Now.AddMinutes(30), model.RememberMe, "Member"); 
            var hashTicket = FormsAuthentication.Encrypt(ticket);
            var userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            Response.Cookies.Add(userCookie);
            return RedirectToLocal(returnUrl);
        }
        ModelState.AddModelError("", "error");
        return View(model);
    }

FormsAuthenticationTicket userData =“Member”

最后,使用构建

中的Membership Role机制

结果还是使用了会员角色内置的机制

mvc3可以读取userData

0 个答案:

没有答案