0

I have identity project as followsL

I created custom identity user ApplicationUser

public class ApplicationUser : IdentityUser
    {
        public string Name { get; set; }
    }

and this is my seeding class

 public class DbInitializer : IDbInitializer
    {
        private readonly AppDBContext _dbContext;
        // this my custom identity identity user 
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        public DbInitializer(AppDBContext dbContext, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
            _roleManager = roleManager;
        }

        public void Initialize()
        {
            if (_roleManager.FindByNameAsync(SD.Admin).Result == null)
            {
                _roleManager.CreateAsync(new IdentityRole(SD.Admin)).GetAwaiter().GetResult();
                _roleManager.CreateAsync(new IdentityRole(SD.Customer)).GetAwaiter().GetResult();

                Debug.WriteLine(_roleManager.FindByIdAsync(SD.Admin));
            }
            else { return; }

            ApplicationUser adminUser = new ApplicationUser()
            {
                UserName = "dodocinaga@gmail.com",
                Email = "dodocinaga@gmail.com",
                EmailConfirmed = true,
                PhoneNumber = "081321857585",
                Name = "nandough admin",
            };

            Debug.WriteLine(adminUser.Id);

            _userManager.CreateAsync(adminUser, "123serV123").GetAwaiter().GetResult();
             // This the error coming from: the AddToRoleAsync
            _userManager.AddToRoleAsync(adminUser, SD.Admin).GetAwaiter().GetResult();

            var claims1 = _userManager.AddClaimsAsync(adminUser, new Claim[] 
            {
                new Claim(JwtClaimTypes.Name, adminUser.Name),
                new Claim(JwtClaimTypes.Role, SD.Admin),
            }).Result;

            ApplicationUser customerUser = new ApplicationUser()
            {
                UserName = "fernando.sinaga@msn.com",
                Email = "fernando.sinaga@msn.com",
                EmailConfirmed = true,
                PhoneNumber = "081321857586",
                Name = "nandough customer",
            };

            _userManager.CreateAsync(customerUser, "12345").GetAwaiter().GetResult();

            _userManager.AddToRoleAsync(customerUser, SD.Customer).GetAwaiter().GetResult();

            var claims2 = _userManager.AddClaimsAsync(customerUser, new Claim[]
            {
                new Claim(JwtClaimTypes.Name, customerUser.Name),
                new Claim(JwtClaimTypes.Role, SD.Customer),
            }).Result;
        }
    }

my program.cs

using Incarnate.Service.Identity;
using Incarnate.Service.Identity.DBContexts;
using Incarnate.Service.Identity.IDbInitializer;
using Incarnate.Service.Identity.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

activate nugget package razor runtimeCompilation

builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();

builder.Services.AddDbContext<AppDBContext>(opt => opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// register my custom identity user here
builder.Services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<AppDBContext>().AddDefaultTokenProviders();

builder.Services.AddScoped<IDbInitializer, DbInitializer>();

builder.Services.AddRazorPages();

// the configuration of identityServer here
builder.Services.AddIdentityServer(options =>
{
    options.Events.RaiseErrorEvents = true;
    options.Events.RaiseSuccessEvents = true;
    options.Events.RaiseInformationEvents = true;
    options.Events.RaiseFailureEvents = true;
    options.EmitStaticAudienceClaim = true;  
}).AddInMemoryIdentityResources(SD.IdentityResources).AddInMemoryApiScopes(SD.ApiScopes).AddInMemoryClients(SD.Clients).AddAspNetIdentity<ApplicationUser>().AddDeveloperSigningCredential();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

// Seed database here
SeeDatabase();

app.UseRouting();

// using the identity server here
app.UseIdentityServer();

app.UseAuthorization();

// using duende razor pages 
app.MapRazorPages().RequireAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

// seed 
void SeeDatabase()
{
    using (var scope = app.Services.CreateScope())
    {
        var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
        dbInitializer.Initialize();
    }
}

the issue occur when I update the project from dotnet 5 to dotnet 6 as well with the duende 6.

The issues:

  1. FK conflict in database when creating new user with it role.
  2. previous version i cheated by having only name in my custom identity user class ApplicationUser.cs so my sql database will refer to default id given by IdentityUser and it worked find before updating.

Any advices guys, Thanks

SOLVED. thanks to @yiyi-you for the references.

  • 1
    You can check if user exists before creating it. Also, please rewrite the code to use async/await. As all these `.Result` and `.GetAwaiter().GetResult()` hurts my eyes. – unsafePtr Oct 03 '22 at 09:35
  • Thank for replying. After couples of debugging, The user was created (UserId) as well as with the role (RoleId), but when assigning role to a user the FK conflict happens. The AspNetUser table can not add user due to conflict with AspNetUserRoles FK UserId. The Databae can not map the UserId and RoleId in AspNetUserRoles. So it has to be the SQl being funny with mapping because UserId exist as well as with RoleId. – Fernando Sinaga Oct 03 '22 at 10:07
  • We usually find the user by Name after creating the user,then use user id to add role to the user.You can refer to the [link](https://stackoverflow.com/questions/19689183/add-user-to-role-asp-net-identity). – Yiyi You Oct 04 '22 at 09:07
  • //.Result and .GetAwaiter().GetResult() hurts my eyes.// Agreed. Please go learn how to properly use await/async instead of "well it works" code........ you're killing the entire async-await paradigm with these. – granadaCoder Oct 05 '22 at 14:50

0 Answers0