using System.Text; using System; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using NLog.Extensions.Logging; using NLog; using gswi.Configuration; using gswi.CredentialManager; using gswi.Data; using gswi.Data.Repositories; using gswi.Filters; using gswi.Interface.Repositories; using gswi.Interface.Services; using gswi.Service; using gswi.SMTP.Interface; using gswi.SMTP.Service; using gswi.SignalR; using Microsoft.AspNetCore.HttpOverrides; namespace gswi { public class Startup { public IConfiguration Configuration { get; } private static Logger _logger = LogManager.GetCurrentClassLogger(); public Startup(IHostEnvironment env) { try { var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrEmpty(environmentName)) environmentName = "production"; var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddJsonFile($"appsettings.{System.Net.Dns.GetHostName()}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } catch (Exception e) { _logger.Error(e); } } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddLogging(builder => { builder.ClearProviders(); builder.AddConfiguration(Configuration.GetSection("Logging")); builder.AddNLog(); builder.AddConsole(); }); var frontend = GetTypedSettingsFromSection("Frontend"); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.WithOrigins(frontend.URL) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() .SetIsOriginAllowed((host) => true)); }); var dbSettings = GetTypedSettingsFromSection("Database"); var authSettings = GetTypedSettingsFromSection("Authentification"); var emailSettings = GetTypedSettingsFromSection("EMail"); var apiSettings = GetTypedSettingsFromSection("API"); emailSettings.Credentials = Base64.Decode(emailSettings.Credentials); services.AddSingleton(dbSettings); services.AddSingleton(authSettings); services.AddSingleton(emailSettings); services.AddSingleton(apiSettings); services.AddSingleton(GetTypedSettingsFromSection("Frontend")); services.AddDbContextPool(opt => opt.UseMySql( Base64.DecodeConnectionString(dbSettings.ConnectionString, dbSettings.Credentials), new MySqlServerVersion(new Version(10, 3, 32)) )); services.AddTransient(); services.AddTransient(); services.AddScoped((s) => s.GetRequiredService()); services.AddScoped((s) => new AuthUserRepositoryImpl((DatabaseContext)s.GetService())); services.AddSignalR(); services.AddAuthentication(opt => { opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(opt => { opt.RequireHttpsMetadata = false; opt.SaveToken = true; opt.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = authSettings.Issuer, ValidAudience = authSettings.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authSettings.SecretKey)) }; }); services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; // options.SerializerSettings.TypeNameHandling = TypeNameHandling.All; }); services.AddControllers(options => { options.Filters.Add(typeof(CustomExceptionFilterAttribute)); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder gswi, IWebHostEnvironment env, ILoggerFactory loggerFactory) { gswi.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); if (env.IsDevelopment()) { gswi.UseDeveloperExceptionPage(); } NLog.LogManager.LoadConfiguration($"nlog-{env.EnvironmentName}.config"); gswi.UseCors("CorsPolicy"); var apiSettings = GetTypedSettingsFromSection("API"); if (apiSettings.RedirectToHTTPS) { gswi.UseHttpsRedirection(); } gswi.UseRouting(); gswi.UseAuthentication(); gswi.UseAuthorization(); gswi.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapHub("/notify"); }); } protected SettingType GetTypedSettingsFromSection(string sectionName) where SettingType : new() { try { var settings = new SettingType(); Configuration.GetSection(sectionName).Bind(settings); return settings; } catch (Exception e) { _logger.Error(e); return new SettingType(); } } } }