using System.Globalization; using System.Net.Mime; using System.Text; using API.Auth; using API.Validation; using DbServices; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Services; var builder = WebApplication.CreateBuilder(args); var config = builder.Configuration; // Add services to the container. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => options.InvalidModelStateResponseFactory = context => new BadRequestObjectResult(context.ModelState) { ContentTypes = { MediaTypeNames.Application.Json } }); builder.Services.AddCors(options => options.AddPolicy("cors", policy => policy .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() )); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer( x => x.TokenValidationParameters = new TokenValidationParameters { IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["JWT:Key"]!)), ValidateLifetime = true, ValidateIssuer = false, ValidateAudience = false, ValidateIssuerSigningKey = true } ); builder.Services.AddAuthorization(options => options.AddPolicy(IdentityData.AdminUserPolicyName, p => p.RequireClaim(IdentityData.AdminUserClaimName))); builder.Services.AddDbContext(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); var app = builder.Build(); System.AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); app.Use((context, next) => { var req = context.Request; Console.WriteLine($"{req.Method}: {req.Path}{req.QueryString}"); return next.Invoke(); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseCors("cors"); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Use((context, next) => { var it = context.User .Claims .FirstOrDefault(c => c.Type == IdentityData.IdUserClaimName) ?.Value; if (it == null) return next.Invoke(); SymmetricSecurityKey key = new(Encoding.UTF8.GetBytes(config["JWT:Key"]!)); var (jwt, expirationDate) = Authentication.GenerateJwt(key, context.User.Claims); context.Response.Headers["Next-Authorization"] = jwt; context.Response.Headers["Next-Authorization-Expiration-Date"] = expirationDate.ToString(CultureInfo.InvariantCulture); context.Response.Headers.AccessControlExposeHeaders = "Next-Authorization, Next-Authorization-Expiration-Date"; return next.Invoke(); }); app.Run();