0

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.

1 Answer 1

0

The problem was that RequireAuthorization should have add Identity Schema:

app.MapGet("/admin/page", () => Results.Ok("admin page"))
  .RequireAuthorization(config =>
  {
    config.AddAuthenticationSchemes(IdentityConstants.BearerScheme);
    config.RequireClaim("is_admin"));
  });
Sign up to request clarification or add additional context in comments.

1 Comment

New ChatGPT 4-o didn't help... 😐

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.