MVC Identity 2使用FormsAuthenticationTicket

时间:2015-01-25 13:40:46

标签: asp.net-mvc-5 forms-authentication asp.net-identity-2

我正在用自定义版本替换(HttpContext.Current.User)IPrincipal,以便我可以存储更多信息登录和用户。我在使用FormsAuthtenticationTicket之前已完成此操作,但其他方式基于Memberhipship和SimpleMembership提供程序。

我的问题是,我可以使用FormsAuthenticationTicket存储我的ICustomPrincipal的cookie,它会干扰或破坏OWIN Identity Pipline吗?我觉得我会混合苹果和橘子。

示例保存:

var user = userRepository.Users.Where(u => u.Email == viewModel.Email).First();

    CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
    serializeModel.UserId = user.Id;
    serializeModel.FirstName = user.FirstName;
    serializeModel.LastName = user.LastName;

    JavaScriptSerializer serializer = new JavaScriptSerializer();

    string userData = serializer.Serialize(serializeModel);

    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
             1,
             viewModel.Email,
             DateTime.Now,
             DateTime.Now.AddMinutes(15),
             false,
             userData);

    string encTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
    Response.Cookies.Add(faCookie);

示例检索:

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

        CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
        newUser.UserId = serializeModel.UserId;
        newUser.FirstName = serializeModel.FirstName;
        newUser.LastName = serializeModel.LastName;

        HttpContext.Current.User = newUser;
    }
}

修改 我有这个用于创建声明

public ClaimsIdentity CreateIdentity(
             LoginAttempt loginAttempt)
        {
            UserProfile userProfile = GetUserProfile(loginAttempt.UserName);

            var applicationUser = FindById(userProfile.AspNetUserId);

            ClaimsIdentity identity;
            try
            {
                 identity = UserManager.CreateIdentity(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);
                return null;
            }
            //UserManager.GetClaims()
            identity.AddClaim(new Claim("LoginAttemptId", loginAttempt.LoginAttemptId.ToString(),ClaimValueTypes.String));
            identity.AddClaim(new Claim("UserProfileId", loginAttempt.UserProfileId.ToString(), ClaimValueTypes.String));
            identity.AddClaim(new Claim("SubscriptionType", userProfile.SubscriptionType, ClaimValueTypes.String));

            IList<string> roles= UserManager.GetRoles(applicationUser.Id);

            identity.AddClaim(new Claim(ClaimTypes.Role, roles.First()));
            return identity;
        }

这用于提取

public static long GetLoginAttemptId(this IIdentity principal)
        {
            var claimsPrincipal = principal as ClaimsIdentity;
            if (claimsPrincipal == null)
            {
                //throw new Exception("User is not logged in!");
                return -1;
            }
            var nameClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "LoginAttemptId");
            if (nameClaim != null)
            {
                return Convert.ToInt64( nameClaim.Value);// as long;
            }

            return -1;
        }

修改 这些是我得到的主张。我已经注销并重新登录。 enter image description here

2 个答案:

答案 0 :(得分:7)

有些声明的目的完全相同。实际上只有新的API才是这样的。

声明基本上是Dictionary<String, String>,存储在auth-cookie中,可通过IPrincipal获取。但是您不需要执行ICustomPrincipal,因为IPrincipal后面的实际对象是ClaimsPrincipal,并且有一个声明列表。

您可以在登录前向Idnentity对象添加额外信息:

public async override Task CreateIdentityAsync(ApplicationUser applicationUser)
{
    var identity = await base.CreateIdentityAsync(applicationUser, DefaultAuthenticationTypes.ApplicationCookie);

    identity.AddClaim(new Claim("MyApp:FullName", applicationUser.FullName));
    return identity;
}

然后您就可以通过扩展程序从IPrincipal获取此数据:

public static String GetFullName(this IPrincipal principal)
{
    var claimsPrincipal = principal as ClaimsPrincipal;
    if (claimsPrincipal == null)
    {
         throw new Exception("User is not logged in!");
    }
    var nameClaim = principal.Claims.FirstOrDefault(c => c.Type == "MyApp:FullName");
    if (nameClaim != null)
    {
        return nameClaim.Value;
    }

    return String.Empty;
}

我已经在一些项目中成功使用了这种方法。有关更多代码示例,请参阅other similar answers 这里是another article,虽然我不鼓励在MVC应用程序中使用Thread.CurrentPrincipalClaimsPrincipal.Current - 但是你并不总能得到你所期望的,特别是当用户没有登录或在早期阶段AppPool启动。

答案 1 :(得分:1)

这种方法对我有用(使用MVC4),与上面略有不同。

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        userIdentity.AddClaim(new Claim("MyApp:OrganizationId", OrganizationID.ToString()));

        return userIdentity;
    }

    public int OrganizationID { get; set; }
}

扩展方法。请注意,您应该使用claimPrincipal变量(而不是主变量)来获取声明。我认为在@trailmax的优秀答案中有点错误(很抱歉没有在你的回答中评论这一点,我的声誉不允许我)。另外,我使用IIdentity而不是IPrincipal

public static class IdentityExtensions
    {
        public static int GetOrganizationId(this IIdentity principal)
        {
            var claimsPrincipal = principal as ClaimsIdentity;
            if (claimsPrincipal == null)
            {
                throw new Exception("User is not logged in!");
            }

            var nameClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "MyApp:OrganizationId");
            if (nameClaim != null)
            {
                return int.Parse(nameClaim.Value);
            }

            throw new Exception("ID doesn't exists");
        }
    }

然后,我在控制器中使用扩展方法,如下所示:

var organizationId = User.Identity.GetOrganizationId();

希望这对某人有用。