using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Converters; 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())); builder.Services.AddOpenApiDocument(); builder.Services.AddOpenApi(); 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.SeedRolesAsync(services).GetAwaiter().GetResult(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); } }