123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170 |
- 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<int>("JwtSettings:ExpirationInHours"))
- };
- });
- services.AddMvc().AddNewtonsoftJson();
- var validOrigins = Configuration.GetSection("RegisteredDomains").Get<List<string>>().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<Startup> logger,
- IApplicationBuilder app,
- IWebHostEnvironment env,
- ICorsService corsService,
- ICorsPolicyProvider corsPolicyProvider
- )
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- if (Configuration.GetValue<Boolean>("UseHttps"))
- {
- app.UseHttpsRedirection();
- }
- string errorPath = Path.Combine(Directory.GetCurrentDirectory(), Configuration.GetValue<string>("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<string>("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");
- }
- }
- }
|