using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using MikrocopApi.Configuration; using MikrocopApi.Extensions; using MikrocopApi.Middleware; using MikrocopApi.Services; using MikrocopDb; using MikrocopDb.Repositories; using Serilog; using Serilog.Formatting.Json; var builder = WebApplication.CreateBuilder(args); var loggerConfiguration = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) .WriteTo.File( formatter: new JsonFormatter(renderMessage: true), path: "Logs/log-.json", rollingInterval: RollingInterval.Day, shared: true); if (builder.Environment.IsDevelopment()) { loggerConfiguration.WriteTo.Console(); } else { loggerConfiguration.WriteTo.Console(new JsonFormatter(renderMessage: true)); } Log.Logger = loggerConfiguration.CreateLogger(); builder.Host.UseSerilog(); builder.Services.Configure(builder.Configuration.GetSection("Jwt")); builder.Services.AddControllers(); builder.Services.AddSwaggerWithJwtAuth(); var jwtOptions = builder.Configuration.GetSection("Jwt").Get() ?? new JwtOptions(); if (string.IsNullOrWhiteSpace(jwtOptions.SigningKey) || jwtOptions.SigningKey.Length < 32) { throw new InvalidOperationException("Jwt:SigningKey must be configured and at least 32 characters long."); } builder.Services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtOptions.Issuer, ValidAudience = jwtOptions.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SigningKey)), ClockSkew = TimeSpan.Zero }; }); builder.Services.AddAuthorization(); builder.Services.AddDbContext(options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddSingleton(); var app = builder.Build(); using (var scope = app.Services.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService(); if (app.Environment.IsDevelopment()) { await dbContext.Database.MigrateAsync(); } else { await dbContext.Database.EnsureCreatedAsync(); } } if (app.Environment.IsDevelopment()) { app.UseSwaggerWithJwtAuth(); } app.UseMiddleware(); app.UseMiddleware(); if (!app.Environment.IsDevelopment()) { app.UseHttpsRedirection(); } app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); await app.RunAsync();