MVC Identity 2 using FormsAuthenticationTicket

后端 未结 2 648
感情败类
感情败类 2020-12-21 13:50

I am replacing the (HttpContext.Current.User) IPrincipal with a custom version so I can store more information login and the user. I have done this before using the FormsAu

2条回答
  •  难免孤独
    2020-12-21 14:23

    This approach works for me (Using MVC4), slightly different from above.

    public class ApplicationUser : IdentityUser
    {
        public async Task GenerateUserIdentityAsync(UserManager 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; }
    }
    

    Extension method. Note you should use claimsPrincipal variable (instead of principal variable) to obtain the claims. I think that's a little mistake in the excelent answer of @trailmax (sorry for not comment this in your answer, my reputation doesn't allow me). Also, I use IIdentity instead of 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");
            }
        }
    

    And then, I use the extension method in the controller like this:

    var organizationId = User.Identity.GetOrganizationId();
    

    Hope this is useful to someone.

提交回复
热议问题