FormsAuthenticationTicket使用Asp.Net MVC 5不将角色传递给global.asax

时间:2015-07-03 12:21:34

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

我正在使用FormsAuthenticationTicket创建角色manullay。我有2个角色(管理员和用户)。我尝试使用FormAuthenticationTicket设置角色但失败了。 global.asax文件中没有角色传递...

这是我的代码:(登录控制器类)

        string[] names = new string[2] { "admin", "user"};
        var ticket = new FormsAuthenticationTicket(
        version: 1,
        name: loginmodel.Email,
        issueDate: DateTime.Now,
        expiration: DateTime.Now.AddMinutes(30),
        isPersistent: false,
        userData: String.Join("|", names));

                var encryptedTicket = FormsAuthentication.Encrypt(ticket);
                var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                HttpContext.Response.Cookies.Add(cookie);

当我检查票证数据时:它包含UserData =" admin | user"但在全局文件中为空。

Global.asax代码:

 public override void Init()
    {

        base.AuthenticateRequest += OnAuthenticateRequest;
    }

    private void OnAuthenticateRequest(object sender, EventArgs eventArgs)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
                var roles = decodedTicket.UserData.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);

                var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
                HttpContext.Current.User = principal;
            }
        }
    }

在var decodeTicket中= UserData始终为null :(

0 个答案:

没有答案