using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthentication(IdentityConstants.ApplicationScheme) .AddIdentityCookies() .ApplicationCookie!.Configure(opt => opt.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = ctx => { ctx.Response.StatusCode = 401; return Task.CompletedTask; } }); builder.Services.AddAuthorizationBuilder(); builder.Services.AddDbContext( options => options.UseInMemoryDatabase("AppDb")); builder.Services.AddIdentityCore() .AddEntityFrameworkStores() .AddApiEndpoints(); // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.MapIdentityApi(); app.UseDefaultFiles(); app.UseStaticFiles(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); // protection from cross-site request forgery (CSRF/XSRF) attacks with empty body // form can't post anything useful so the body is null, the JSON call can pass // an empty object {} but doesn't allow cross-site due to CORS. app.MapPost("/logout", async ( SignInManager signInManager, [FromBody]object empty) => { if (empty is not null) { await signInManager.SignOutAsync(); return Results.Ok(); } return Results.NotFound(); }).RequireAuthorization(); 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.MapFallbackToFile("/index.html"); app.Run(); internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); } class MyUser : IdentityUser { } class AppDbContext(DbContextOptions options) : IdentityDbContext(options) { }