using AuthApi.Services; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using SystemX.Core.Services; using WebApi.Library.Config; string configDir = @"../../Config"; string configFileName = "WebApi.AuthApi.Config.json"; //raed log4net configs if (LogXnet.ReadConfig(@$"{configDir}/LogXnetConfig.json") == true) { LogXnet.WriteLine("LogXnet Init Success"); } else { Console.WriteLine("LogXnet Init Failed"); return; } var builder = WebApplication.CreateBuilder(args); // Add services to the container. //singleton builder.Services.AddSingleton>(); //scoped builder.Services.AddScoped(); //db builder.Services.AddSingleton(); // Generic µî·Ï builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddHttpContextAccessor(); //config preload, auth set ConfigService preloadConfig = new ConfigService(); if (preloadConfig.OpenConfig($@"{configDir}/{configFileName}") == true) { var config = preloadConfig.GetConfig(); //auth builder.Services .AddAuthentication(option => { option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ClockSkew = TimeSpan.Zero, ValidIssuer = $"{config?.Auth?.issuer}", ValidAudience = $"{config?.Auth?.audience}", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes($"{config?.Auth?.accessTokenSecret}")) }; }); } else { LogXnet.WriteLine("Config Preload Load Error.", LogXLabel.Error); return; } var app = builder.Build(); //read api config and set string serverUrl = string.Empty; var configService = app.Services.GetService>(); bool isIIS = false; if (configService?.OpenConfig($@"{configDir}/{configFileName}") == true) { LogXnet.WriteLine("WebApi Config Success."); var apiConfig = ConfigService.Config; if (apiConfig != null) { serverUrl = $"{apiConfig?.Server?.Address}:{apiConfig?.Server?.Port}"; isIIS = apiConfig!.Server.IIS; using(var scoped = app.Services.CreateScope()) { var dbProvider = scoped.ServiceProvider.GetRequiredService(); dbProvider?.SetDBList(apiConfig?.DataBase); } } } else { LogXnet.WriteLine("WebApi Config Error."); return; } // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { LogXnet.WriteLine($"IsDevelopment:{app.Environment.IsDevelopment()}"); LogXnet.WriteLine($"Swagger Url: {serverUrl}/swagger"); app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthentication(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); if (isIIS == true) { app.Run(); } else { LogXnet.WriteLine($"Operation Url: {serverUrl}"); app.Run($"{serverUrl}"); }