Search code examples
c#asp.net-core.net-coreentity-framework-coreidentity

.NET Core / Entity Framework Core : extract custom field from UserRoles table


I have customized the EF Core identity model to have additional information on the UserRole relationship.

Now, I would like to extract the custom fields added once the user logs in, so I can pass them to the application.

Below are the created classes and the method in which I retrieve the user's information.

public class ApplicationUser: IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; } = null!;
    public string? UserCode { get; set; } = null!;
    public string? UserExternalCode1 { get; set; } = null!;
    public string? UserExternalCode2 { get; set; } = null!;
    public string? UserExternalCode3 { get; set; } = null!;
    public Guid? EmployeeTypeId { get; set; }
    public EmployeeType? EmployeeType { get; set; } = null!;
}

public class ApplicationUserRole: IdentityUserRole<string>
{
    public Guid? LineId { get; set; }
    public Line? Line { get; set; } = null!;
    public Guid? TerritoryId { get; set; }
    public Territory? Territory { get; set; } = null!;
    public Guid? BusinessUnitId { get; set; }
    public BusinessUnit? BusinessUnit { get; set; } = null!;
    public DateTimeOffset ValidFrom { get; set; }
    public DateTimeOffset? ValidTo { get; set; }
}

ApplicationDbContext:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
     {
     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         base.OnModelCreating(modelBuilder);

         // User Management
         modelBuilder.Entity<IdentityUser>().ToTable("Users");
         modelBuilder.Entity<IdentityRole>().ToTable("Roles");
         modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RolesClaims");
         modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UsersClaims");
         modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UsersLogins");
         modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UsersRoles");
         modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UsersTokens");

         modelBuilder.Entity<ApplicationUser>().Property(p => p.UserCode).HasMaxLength(100);
         modelBuilder.Entity<ApplicationUser>().Property(p => p.UserExternalCode1).HasMaxLength(100);
         modelBuilder.Entity<ApplicationUser>().Property(p => p.UserExternalCode2).HasMaxLength(100);
         modelBuilder.Entity<ApplicationUser>().Property(p => p.UserExternalCode3).HasMaxLength(100);

         modelBuilder.Entity<ApplicationUserRole>().Property(p => p.ValidFrom).HasDefaultValue(DateTimeOffset.Now);
    }

    // User Management
    public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; }
}

Extract user and role info:

private static async Task<AuthenticationResponseDTO> BuildToken(UsersCredentialsDTO usersCredentialsDTO, IConfiguration configuration, UserManager<IdentityUser> userManager)
{
     var claims = new List<Claim>
     {
         new Claim("email", usersCredentialsDTO.Email)
     };

     var user = await userManager.FindByEmailAsync(usersCredentialsDTO.Email);
     
     var claimsFromDB = await userManager.GetClaimsAsync(user!);
     var userId = await userManager.GetUserIdAsync(user!);
     var roles = await userManager.GetRolesAsync(user!);
     var userName = await userManager.GetUserNameAsync(user!);

     claims.AddRange(claimsFromDB);

     var key = KeysHandler.GetKey(configuration).First();
     var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

     var expiration = DateTime.UtcNow.AddDays(1);

     var securityToken = new JwtSecurityToken(issuer: null, audience: null, claims: claims, expires: expiration, signingCredentials: credential);

     var token = new JwtSecurityTokenHandler().WriteToken(securityToken);

     return new AuthenticationResponseDTO
     {
         Token = token,
         Id = new Guid(userId),
         Roles = roles,
         Email = userName,
         Claims = claims,
         Expiration = expiration
     };
}

This line of code

var roles = await userManager.GetRolesAsync(user!);

is currently returning only the role Name without the new information added to the entity.

Could someone help me?

I'm quite new to Entity Framework Core, so probably I'm missing some basics


Solution

  • If you check the source code of GetRolesAsync ,it is Task<IList<string>> GetRolesAsync(TUser user) which returns a IList<string> of the role names. But what you need to return is List<ApplicationUser>. So we have to write an extenstion method for UserManager. You could try following code:
    ApplicationRole.cs

        public class ApplicationRole : IdentityRole
        {
            public string addtionalRoleInfo { get; set; }
        }
    

    UserManagerExtensions.cs

        public static class UserManagerExtensions
        {
            public static async Task<IList<ApplicationRole>> GetAppRoles(this UserManager<IdentityUser> userManager, IdentityUser user, ApplicationDbContext dbContext)
            {
                var appRoles = new List<ApplicationRole>();
                var userRoles = dbContext.UserRoles.Where(x => x.UserId == user.Id);
    //get the role names using "GetRolesAsync"
                var roles = await userManager.GetRolesAsync(user);
    
                foreach (var role in roles)
                {
    //using the role names to get the full ApplicaitonRole informations from Roles table.
                    var appRole =dbContext.Roles.First(x=>x.Name==role);
                    appRoles.Add(appRole);
                }
                return appRoles;
            }
        }
    

    Then test with following:

        public class ValuesController : ControllerBase
        {
            private readonly UserManager<IdentityUser> _userManager;
            private readonly RoleManager<ApplicationRole> _roleManager;
            private readonly ApplicationDbContext _dbContext;
    
            public ValuesController(UserManager<IdentityUser> userManager,RoleManager<ApplicationRole> roleManager,ApplicationDbContext dbContext)
            {
                this._userManager = userManager;
                this._roleManager = roleManager;
                this._dbContext = dbContext;
            }
    
            //To register a user "[email protected]" with role "Admin" and "IT"
            [HttpGet("initial")]
            public async Task initial()
            {
                var newuser = new IdentityUser { Email = "[email protected]" ,UserName="Tom"};
                await _userManager.CreateAsync(newuser, "Q!q11111");
    
                await _roleManager.CreateAsync(new ApplicationRole { Id = "1", Name = "Admin", addtionalRoleInfo = "administrator" });
                await _roleManager.CreateAsync(new ApplicationRole { Id = "2", Name = "IT", addtionalRoleInfo = "information technology" });
    
                var user = await _userManager.FindByEmailAsync("[email protected]");
                await _userManager.AddToRoleAsync(user,"Admin");
                await _userManager.AddToRoleAsync(user, "IT");
            }
            //test to get roles
            [HttpGet("getroles")]
            public async Task<List<ApplicationRole>> GetRoles()
            {
                var user =await _userManager.FindByEmailAsync("[email protected]");
                var approles =await _userManager.GetAppRoles(user,_dbContext);
                return approles.ToList();
            }
        }
    

    Test result
    enter image description here