本文介绍了经与窗体身份验证角色麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用MVC 4窗体身份验证(我使用RavenDB所以我不能使用标准的会员供应商)的用户进行身份验证。再后来我使用 User.IsInRole()方法或 AuthorizeAttribute 来验证用户在工作人员的作用

I'm trying to authenticate a user using forms authentication in MVC 4 (I'm using RavenDB so I can't use the standard membership providers). Then later I'm using the User.IsInRole() method or AuthorizeAttribute to verify the user is in a staff role.

下面就是我设置成功验证票(在此刻 UserController.cs

Here's where I set the ticket on successful authentication (at the moment in 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);

下面就是我查票为每个请求(的Global.asax

Here's where I check the ticket for each request (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;
    }
}

如果我再放入一个调试点对我的行为方式(CalendarController.cs)之一,我得到 isStaff 等于

If I then put a debug point on one of my action methods (CalendarController.cs), I get isStaff equals false:

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

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

    return View();
}

刚刚完成(Roles.cs,只是一个暂时的类来测试的东西):

Just for completion (Roles.cs, just a temporary class to test things):

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

    public static string Manager
    {
        get { return "Manager"; }
    }
}

谁能帮给我一个点,以什么我可能会丢失?它看起来好像我设置的角色的时候,我得到的操作方法消失。

Can anyone help give me a point as to what I might be missing? It looks as though the roles I set are disappearing by the time I get to the action method.

推荐答案

谢谢你们帮助我这一点,我想出了(包括以下)的伟大工程!它自动记录用户直接通过他们是否有一个有效的票证(饼干)的登录屏幕,也可以处理索赔使用基于角色的 ClaimsIdentity ClaimsPrincipal 的对象,没有把角色在用户的cookie。它也处理在的Global.asax.cs 文件验证,而不必诉诸投入定制的授权属性。

Thanks guys for helping me with this, what I've come up with (included below) works great! It auto-logs users straight in through the login screen if they have a valid ticket (cookie) and also handles Claims based roles using the ClaimsIdentity and ClaimsPrincipal objects, without putting the roles in the user's cookie. It also handles authentication in the Global.asax.cs file without having to resort to putting in custom authorize attributes.

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");
}

的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;
    }
}

这篇关于经与窗体身份验证角色麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:49