.net-coreasp.net-core-identity

Not seeing default endpoint profided by .NET Core Identity if I use IdentityRole


I want to use IdentityRole and also the default endpoint provided by .NET Identity like /login. When I run the the project in swagger, I see all my own endpoints, but not /login.

I want to use the default /login endpoint provided by .NET Core identity.

I am getting the default endpoint if I remove this code:

builder.Services
       .AddIdentity<AppUser, IdentityRole>()
       .AddEntityFrameworkStores<ApplicationDbContext>()
       .AddDefaultTokenProviders();

and I use this instead:

builder.Services
       .AddIdentityApiEndpoints<AppUser>()
       .AddEntityFrameworkStores<ApplicationDbContext>(); 

but then I loose Identity.

Here is my program.cs:

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(option =>
{
    option.AddSecurityDefinition("oauth2", new 
    Microsoft.OpenApi.Models.OpenApiSecurityScheme
    {
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });
    option.OperationFilter<SecurityRequirementsOperationFilter>();
});
builder.Services.AddApplicationInsightsTelemetry();

// Add services to the container
builder.Services.AddControllers().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

// Add Identity with Roles
builder.Services
       .AddIdentity<AppUser, IdentityRole>()
       .AddEntityFrameworkStores<ApplicationDbContext>()
       .AddDefaultTokenProviders();

// Add Authentication
builder.Services.AddAuthentication();
//builder.Services.AddIdentityApiEndpoints<AppUser>()
//    .AddEntityFrameworkStores<ApplicationDbContext>();

// Add Authorization
builder.Services.AddAuthorization();

// Add CORS
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(CorsPolicyBuilder =>
    {
        CorsPolicyBuilder.AllowAnyOrigin();
        CorsPolicyBuilder.AllowAnyHeader();
        CorsPolicyBuilder.AllowAnyMethod();
    });
});

// Add IHttpContextAccessor service
builder.Services.AddHttpContextAccessor();

// Configure Forwarded Headers Middleware
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor |         ForwardedHeaders.XForwardedProto;
    options.KnownProxies.Add(System.Net.IPAddress.Parse("127.0.0.1")); // Adjust     according to your setup
});

// Role seeding method
async Task SeedRoles(IServiceProvider serviceProvider)
{
    var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var roles = new List<string> { "SchoolOwner", "Student", "Teacher", "Parent" }; 

    foreach (var role in roles)
    {
        if (!await roleManager.RoleExistsAsync(role))
        {
            await roleManager.CreateAsync(new IdentityRole(role));
        }
    }
}

var app = builder.Build();

// Call the role seeding method during app startup
using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;
    await SeedRoles(services);
}

app.MapControllers(); // Ensure this is included to map your API controllers

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors();
app.UseHttpsRedirection();

// Enable Forwarded Headers Middleware
app.UseForwardedHeaders();

app.UseAuthentication();
app.UseAuthorization();

app.Run();

Solution

  • According to your program.cs codes, you don't specify the identity api route .

    I suggest you could try to add the route as below to see if this will work well or not.

    app.MapIdentityApi<IdentityUser>();
    

    More details, you could refer to this sample:

    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    // Authorization
    builder.Services.AddAuthorization();
    
    // Configure identity database access via EF Core.
    builder.Services.AddDbContext<ApplicationDbContext>(
        options => options.UseInMemoryDatabase("AppDb"));
    
    // Activate identity APIs. By default, both cookies and proprietary tokens
    // are activated. Cookies will be issued based on the `useCookies` querystring
    // parameter in the login endpoint.
    builder.Services.AddIdentityApiEndpoints<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
     
    // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
    
    app.UseHttpsRedirection();
    
    var summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    
    app.MapGet("/weatherforecast", () =>
    {
        var forecast = Enumerable.Range(1, 5).Select(index =>
            new WeatherForecast
            (
                DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                Random.Shared.Next(-20, 55),
                summaries[Random.Shared.Next(summaries.Length)]
            ))
            .ToArray();
        return forecast;
    })
    .WithName("GetWeatherForecast")
    .WithOpenApi()
    .RequireAuthorization();
    
    app.MapIdentityApi<IdentityUser>();
    
    app.Run();