Role based authorization not working in .net 5
If you have a custom User that inherits from IdentityUser
For example:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
And you have your services configured properly, like so:
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>() /* Added role manager*/
.AddDefaultUI()
.AddEntityFrameworkStores<ApplicationDbContext>();
That should work fine if you are not using a custom claim principal for UserPrincipal.
For example:
public class AppUserClaimsIdentityFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
public AppUserClaimsIdentityFactory(
UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor)
{
}
/* code implementation */
}
and injected it using DI like below:
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppUserClaimsIdentityFactory>();
In that case it doesn't work, you'll need to use a different constructor overload for UserClaimsPrincipalFactory and add role manager to it.
Update your custom UserClaimsIdentityFactory:
public class AppUserClaimsIdentityFactory :
UserClaimsPrincipalFactory<ApplicationUser,
IdentityRole>
/* Note: you can use your custom Role class or identity default */
{
public AppUserClaimsIdentityFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager, /* Add role manager */
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, roleManager /* send it to base constructor */, optionsAccessor)
{
}
/* code implementation */
}
You don't have to change anything in Dependency Injection container for your custom UserClaimsPrincipalFactory.
Everything thing should work fine as expected.