I have the following setup:
var services = builder.Services;
services.AddAuthentication(IdentityConstants.BearerScheme)
.AddBearerToken(IdentityConstants.BearerScheme);
services.AddAuthorizationBuilder()
.SetDefaultPolicy(new([new DenyAnonymousAuthorizationRequirement()],
[IdentityConstants.BearerScheme]));
services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddClaimsPrincipalFactory<AppUserClaimsPrincipalFactory>();
AppUser:
public class AppUser : IdentityUser
{
public string? Locale { get; set; }
public bool? IsAdmin { get; set; }
}
AppUserClaimsPrincipalFactory:
public class AppUserClaimsPrincipalFactory
: UserClaimsPrincipalFactory<AppUser>
{
public AppUserClaimsPrincipalFactory(
UserManager<AppUser> userManager,
IOptions<IdentityOptions> optionsAccessor)
: base(userManager, optionsAccessor) { }
protected override async Task<ClaimsIdentity> GenerateClaimsAsync(AppUser user)
{
var identity = await base.GenerateClaimsAsync(user);
if (user.Locale is not null)
{
identity.AddClaim(new Claim("locale", user.Locale));
}
if (user.IsAdmin == true) //IsAdmin is bool?
{
identity.AddClaim(new Claim("is_admin", "is_admin"));
}
return identity;
}
}
Endpoint causing error:
app.MapGet("/admin/page", () => Results.Ok("admin page"))
.RequireAuthorization(config => config.RequireClaim("is_admin"));
When I call this endpoint, I get 404 Not Found error. I checked that I have required is_admin claim:
app.MapGet("/claims", async (SignInManager<AppUser> signInManager, HttpContext http) =>
{
var user = await signInManager.UserManager.GetUserAsync(http.User);
if (user is null)
{
return Results.BadRequest("User not found");
}
var principal = await signInManager.CreateUserPrincipalAsync(user);
return Results.Ok(principal.Claims);
})
.RequireAuthorization();
However, for some reason I get 404 error.