using DamageAssesment.Api.UsersAccess.Db; using DamageAssesment.Api.UsersAccess.Interfaces; using DamageAssesment.Api.UsersAccess.Providers; using DamageAssesment.Api.UsersAccess.Models; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using System.Text; using Polly; using DamageAssesment.Api.UsersAccess.Services; using Microsoft.OpenApi.Models; using System.Reflection; using Microsoft.AspNetCore.Authorization; const int maxApiCallRetries = 3; const int intervalToRetry = 2; //2 seconds const int maxRetryForCircuitBraker = 5; const int intervalForCircuitBraker = 5; //5 seconds var builder = WebApplication.CreateBuilder(args); builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => { build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); })); builder.Services.AddLogging(builder => { //builder.AddConsole(); // Optional: Add other providers if needed builder.AddFile("logs/UserAccess-{Date}.txt"); // Specify the file path and format }); // Add services to the container. var authkey = builder.Configuration.GetValue("JwtSettings:securitykey"); var mode = builder.Configuration.GetValue("ModeSettings:mode"); builder.Services.AddAuthentication(). AddJwtBearer("DamageApp", item => { item.RequireHttpsMetadata = true; item.SaveToken = true; item.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)), ValidateIssuer = false, ValidateAudience = false, ClockSkew = TimeSpan.Zero }; }).AddJwtBearer("Dadeschools", options => { options.Authority = builder.Configuration["Dadeschools:Authority"]; options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" }; options.TokenValidationParameters.ValidateAudience = false; }); builder.Services.AddAuthorization(options => { var DamageAppPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes("DamageApp") .Build(); var DadeschoolsPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser() .AddAuthenticationSchemes("Dadeschools") .Build(); var DadeschoolsPolicyOffline = new AuthorizationPolicyBuilder().RequireAssertion(_ => true) .Build(); var allPolicy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .AddAuthenticationSchemes("DamageApp", "Dadeschools") .Build(); options.AddPolicy("DamageApp", DamageAppPolicy); options.AddPolicy("Dadeschools", mode == "online" ? DadeschoolsPolicy : DadeschoolsPolicyOffline); options.AddPolicy("AllPolicies", allPolicy); options.DefaultPolicy = options.GetPolicy("DamageApp")!; }); var _jwtsettings = builder.Configuration.GetSection("JwtSettings"); builder.Services.Configure(_jwtsettings); builder.Services.AddHttpContextAccessor(); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient(). AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); //builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(options => { // Include XML comments from your assembly var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); //options.IncludeXmlComments(xmlPath); OpenApiSecurityScheme securityDefinition = new OpenApiSecurityScheme() { Name = "Bearer", BearerFormat = "JWT", Scheme = "bearer", Description = "Specify the authorization token.", In = ParameterLocation.Header, Type = SecuritySchemeType.Http, }; options.AddSecurityDefinition("jwt_auth", securityDefinition); // Make sure swagger UI requires a Bearer token specified OpenApiSecurityScheme securityScheme = new OpenApiSecurityScheme() { Reference = new OpenApiReference() { Id = "jwt_auth", Type = ReferenceType.SecurityScheme } }; OpenApiSecurityRequirement securityRequirements = new OpenApiSecurityRequirement() { {securityScheme, new string[] { }}, }; options.AddSecurityRequirement(securityRequirements); }); builder.Services.AddDbContext(option => { option.UseSqlServer("UsersAccessConnection"); }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); using (var serviceScope = app.Services.CreateScope()) { var services = serviceScope.ServiceProvider; var usersAccessProvider = services.GetRequiredService(); usersAccessProvider.seedData(); } } app.UseCors("DamageAppCorsPolicy"); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.Run();