基于声明的表单身份验证角色

Adr*_*ips 4 c# asp.net-mvc-3 asp.net-mvc-4

我正在尝试使用MVC 4中的表单身份验证对用户进行身份验证(我正在使用RavenDB,因此我无法使用标准成员资格提供程序).然后我会使用该User.IsInRole()方法或AuthorizeAttribute验证用户是否担任员工角色.

这是我在成功验证时设置票证的地方(目前在UserController.cs):

FormsAuthenticationTicket ticket =
    new FormsAuthenticationTicket(
        1,
        model.Email,
        DateTime.Now,
        DateTime.Now.AddDays(1),
        false,
        model.Email);

string hashedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie =
    new HttpCookie(
        FormsAuthentication.FormsCookieName,
        hashedTicket);

HttpContext.Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

这是我检查每个请求(Global.asax)的票证的地方:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        var user = this.UserService.GetUserByEmail(authTicket.Name);

        var identity = new GenericIdentity(authTicket.Name, "Forms");

        var principal = new GenericPrincipal(identity, user.Roles);

        HttpContext.Current.User = principal;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我然后在我的一个动作方法(CalendarController.cs)上放置一个调试点,我得到isStaff等于false:

public ActionResult Index()
{
    var user = HttpContext.User;

    bool isStaff = user.IsInRole(Role.Staff);

    return View();
}
Run Code Online (Sandbox Code Playgroud)

只是为了完成(Roles.cs,只是一个测试事物的临时类):

public static class Role
{
    public static string Staff
    {
        get { return "Staff"; }
    }

    public static string Manager
    {
        get { return "Manager"; }
    }
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解释一下我可能会缺少什么吗?看起来,当我进入action方法时,我设置的角色正在消失.

Adr*_*ips 8

谢谢大家帮我解决这个问题,我提出的(包含在下面)效果很好!如果用户拥有有效的票证(cookie)并且还使用ClaimsIdentityClaimsPrincipal对象处理基于声明的角色,则可以通过登录屏幕直接自动记录用户,而无需将角色放在用户的cookie中.它还处理Global.asax.cs文件中的身份验证,而无需使用自定义授权属性.

UserController.cs

public ActionResult Login()
{
    LoginViewModel model = new LoginViewModel();

    if ((HttpContext.User != null) &&
        (HttpContext.User.Identity.IsAuthenticated))
    {
        return RedirectToAction("Index", "Home");
    }

    return View(model);
}

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    bool isAuthenticated = this.userService.IsPasswordValid(model.Email, model.Password);

    if (!isAuthenticated)
    {
        ModelState.AddModelError("AuthError", Resources.User.Login.AuthError);

        return View(model);
    }

    FormsAuthentication.SetAuthCookie(model.Email, model.RememberUser);

    return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)

的Global.asax.cs

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        var ticket = FormsAuthentication.Decrypt(authCookie.Value);

        FormsIdentity formsIdentity = new FormsIdentity(ticket);

        ClaimsIdentity claimsIdentity = new ClaimsIdentity(formsIdentity);

        var user = this.UserService.GetUserByEmail(ticket.Name);

        foreach (var role in user.Roles)
        {
            claimsIdentity.AddClaim(
                new Claim(ClaimTypes.Role, role));
        }

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

        HttpContext.Current.User = claimsPrincipal;
    }
}
Run Code Online (Sandbox Code Playgroud)