Reputation: 1032
I am working on an application with authentication. I am using the following frameworks:
For seeding I created a DataSeeder
class, that gets added as Transient Service in the ConfigureServices
function and later called in the Configure function. It checks whether an IdentityUser
exists, and if not it creates one called admin and adds the role Admin to it.
However, when adding the role to the user, I get an exception saying that a foreign key constraint gets violated and that the ASP_NET_USERS does not contain an entry with that PK.
I checked the database and it does indeed contain the new Role that I created, but the user table is still empty.
Here is my DataSeeder
class:
public class DataSeeder {
private DatabaseContext _context;
private UserManager<IdentityUser> _userManager;
private RoleManager<IdentityRole> _roleManager;
public DataSeeder(DatabaseContext ctx, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager) {
_context = ctx;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task CreateUserAsync() {
if (! await _userManager.Users.AnyAsync()) {
var adminRole = new IdentityRole("admin");
var rootRole = new IdentityRole("root");
await _roleManager.CreateAsync(adminRole);
await _roleManager.CreateAsync(rootRole);
var user = new IdentityUser {
Email = "[email protected]",
EmailConfirmed = true,
UserName = "superadmin"
};
await _userManager.CreateAsync(user, "P@SSWORD");
await _userManager.AddClaimAsync(user, new Claim("role", "admin"));
}
}
}
So the exception is thrown at AddClaimAsync
. Any help would be really appreciated
Upvotes: 1
Views: 837
Reputation: 4553
Check the result of _userManager.createAsync
.
var result = await _userManager.CreateAsync(user, "P@SSWORD");
if (!result.Succeeded)
{
// something went wrong, inspect the errors
}
You'll most likely find a required property on your IdentityUser
is missing or the password is not valid.
Upvotes: 1