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:
- FK conflict in database when creating new user with it role.
- 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.