using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.FileProviders; using System.IO; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.Extensions.Logging; using System.Collections.Generic; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.StaticFiles; namespace jsonjumble { public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecretKey"])), ValidateIssuer = true, ValidIssuer = Configuration["JwtSettings:Issuer"], ValidateAudience = true, ValidAudience = Configuration["JwtSettings:Audience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(Configuration.GetValue("JwtSettings:ExpirationInHours")) }; }); services.AddMvc().AddNewtonsoftJson(); var validOrigins = Configuration.GetSection("RegisteredDomains").Get>().ToArray(); var originString = new StringBuilder(); originString.AppendJoin(", ", validOrigins); Console.WriteLine($"Allowing Origins: {originString}"); services.AddCors(options => { // options.AddDefaultPolicy(policy => // { // policy.WithOrigins(validOrigins); // policy.WithMethods(new string[] { "GET" }); // policy.WithHeaders(new string[] { "Access-Control-Allow-Origin", "Content-Type" }); // }); options.AddPolicy(name: "jsonjumble_corspolicy", policy => { // policy.AllowAnyOrigin(); // policy.AllowAnyMethod(); // policy.AllowAnyHeader(); policy.WithOrigins(validOrigins); policy.WithMethods(new string[] {"GET"}); policy.WithHeaders(new string[] {"Access-Control-Allow-Origin", "Content-Type"}); }); }); } public void Configure( ILogger logger, IApplicationBuilder app, IWebHostEnvironment env, ICorsService corsService, ICorsPolicyProvider corsPolicyProvider ) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } if (Configuration.GetValue("UseHttps")) { app.UseHttpsRedirection(); } string errorPath = Path.Combine(Directory.GetCurrentDirectory(), Configuration.GetValue("RelativeErrorFilePath")); logger.LogInformation($"Loading static error pages from {errorPath}"); app.UseStatusCodePages(new StatusCodePagesOptions() { HandleAsync = async (context) => { var filePath = Path.Combine(errorPath, context.HttpContext.Response.StatusCode + ".html"); var responseMessage = $"Error {context.HttpContext.Response.StatusCode}"; if (System.IO.File.Exists(filePath)) { responseMessage = System.IO.File.ReadAllText(filePath); } await context.HttpContext.Response.WriteAsync(responseMessage); } }); string staticPath = Path.Combine(Directory.GetCurrentDirectory(), Configuration.GetValue("RelativeStaticFilePath")); logger.LogInformation($"Loading static files from {staticPath}"); PhysicalFileProvider staticFileProvider = new PhysicalFileProvider(staticPath); app.UseDefaultFiles(new DefaultFilesOptions() { FileProvider = staticFileProvider, DefaultFileNames = new string[] { "index.html", "index.json" } }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = staticFileProvider, ServeUnknownFileTypes = true, OnPrepareResponse = (ctx) => { AddCorsHeadersToStaticFiles(ctx, corsService, corsPolicyProvider); } }); app.UseRouting(); // app.UseCors("jsonjumble_corspolicy"); app.UseCors("jsonjumble_corspolicy"); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } public void AddCorsHeadersToStaticFiles(StaticFileResponseContext ctx,ICorsService corsService,ICorsPolicyProvider corsPolicyProvider) { var policy = corsPolicyProvider.GetPolicyAsync(ctx.Context, "jsonjumble_corspolicy") .ConfigureAwait(false) .GetAwaiter().GetResult(); var corsResult = corsService.EvaluatePolicy(ctx.Context, policy); corsService.ApplyResult(corsResult, ctx.Context.Response); // ctx.Context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); } } }