using System.Net; using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Converters; using NSwag; using NSwag.Generation.Processors.Security; using T120B165_ImgBoard.Data; using T120B165_ImgBoard.Models; using T120B165_ImgBoard.Services; namespace T120B165_ImgBoard; public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); builder.Services.AddAuthorization(); // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddControllers() .AddNewtonsoftJson( options => options.SerializerSettings.Converters.Add(new StringEnumConverter())) /*.ConfigureApiBehaviorOptions(opt => { opt.InvalidModelStateResponseFactory = context => { var problemDetails = new ValidationProblemDetails(context.ModelState); var isBindingError = context.ModelState.Values.Any(v => v.ValidationState == ModelValidationState.Invalid && v.Errors.Any(e => e.Exception is not null || (!string.IsNullOrWhiteSpace(e.ErrorMessage) && e.ErrorMessage.Contains("body is required.")) )); if (isBindingError) { problemDetails.Status = StatusCodes.Status400BadRequest; return new BadRequestObjectResult(problemDetails); } problemDetails.Status = StatusCodes.Status422UnprocessableEntity; var result = new ObjectResult(problemDetails) { StatusCode = StatusCodes.Status422UnprocessableEntity, }; result.ContentTypes.Add("application/json"); return result; }; })*/; builder.Services.AddOpenApiDocument(cfg => { cfg.OperationProcessors.Add(new OperationSecurityScopeProcessor("auth")); cfg.DocumentProcessors.Add(new SecurityDefinitionAppender("auth", new OpenApiSecurityScheme { Type = OpenApiSecuritySchemeType.Http, In = OpenApiSecurityApiKeyLocation.Header, Scheme = "bearer", BearerFormat = "jwt" })); }); builder.Services.AddCors(); builder.Services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); // If we're in dev environment, use in-memory database if (builder.Environment.IsDevelopment()) { builder.Services.AddDbContext(options => options.UseInMemoryDatabase("T120B165_ImgBoard")); } else { Console.WriteLine("Running in production mode"); builder.Services.AddDbContext(options => options.UseMySql( builder.Configuration.GetConnectionString("DbContext"), new MySqlServerVersion(new Version(11, 8, 3)) ) ); } var jwtSettings = builder.Configuration.GetSection("Jwt"); var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtSettings["Issuer"], ValidAudience = jwtSettings["Audience"], IssuerSigningKey = new SymmetricSecurityKey(key) }; }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { //app.MapOpenApi(); app.UseOpenApi(); app.UseSwaggerUi(); } using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService(); context.Database.EnsureCreated(); DbInitializer.SeedAuth(services).GetAwaiter().GetResult(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // allow any origin //.WithOrigins("https://localhost:44351")); // Allow only this origin can also have multiple origins separated with comma .AllowCredentials()); // allow credentials app.MapControllers(); app.Run(); } }