Search code examples
c#asp.net-mvcasp.net-identityclaims-based-identity

How to extend User Identity with an IEnumerable/Collection property


Similar to this question: How to extend available properties of User.Identity

When a user logs in I'd like to load the departments my user has an association with. I'm guessing that I'd add a property to the ApplicationUser class like this:

public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            return userIdentity;
        }


        public IEnumerable<Department> Departments { get; set; }
    }

My question is how/where would I populate the collection, and then how would I access the property later in my controllers. From what I understand, claims would be OK for simple types - an Id for example - but can they be used with collections?

I'm assuming once I have this property loaded, I'd be able to query the collection without hitting the database each time I need this information about the user - which will be often.

Any help appreciated.


Solution

  • First of all, create the collection entity, i.e. Department. Then reference the Id of the ApplicationUser entity within that.

    Assuming you use entity framework code-first, here is an example:

    public class ApplicationUser : IdentityUser<Guid, GuidUserLogin, GuidUserRole, GuidUserClaim>
        {
            public async Task<ClaimsIdentity> GenerateUserIdentityAsync(ApplicationUserManager manager)
            {
                // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
                var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
                return userIdentity;
            }
    
            public ApplicationUser()
            {
               Departments = new Collection<Department>();
            }
    
            public ICollection<Department> Departments { get; set; }
        }
    
    
    
    public class Department
    {
    
        public string UserId { get; set; }
    
        public int DepartmentId { get; set; }
    
        public ApplicationUser User { get; set; }
    
        protected Department()
        {
    
        }
    
    }