// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } var swaggerOptions = new MySwaggerOptions(); Configuration.GetSection(nameof(swaggerOptions)).Bind(swaggerOptions); app // new .net core routing services required before using middleware .UseRouting() // exception handling as Internal server error output .UseMiddleware(typeof(ExceptionHandlingMiddleware)) // swagger .UseSwagger(option => option.RouteTemplate = swaggerOptions.JsonRoute) .UseSwaggerUI(option => option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description)) // redirection .UseHttpsRedirection() // new endpoint resources registrations .UseEndpoints(e => e.MapControllers()); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IdentityContext identityContext, ApiContext apiContext) { if (env.IsDevelopment()) { // for development purposes, migrate any database changes on startup (includes initial db creation) apiContext.Database.Migrate(); identityContext.Database.Migrate(); app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } var swaggerOptions = new MySwaggerOptions(); Configuration.GetSection(nameof(swaggerOptions)).Bind(swaggerOptions); app.UseMiddleware(typeof(ExceptionMiddleware)); if (!env.IsProduction()) { app.UseSwagger(option => option.RouteTemplate = swaggerOptions.JsonRoute) .UseSwaggerUI(option => option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description)); } app.UseHttpsRedirection() .UseRouting() .UseAuthentication() .UseAuthorization() .UseEndpoints(e => e.MapControllers()); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { // Add framework services. services .AddMvc(options => { options.InputFormatters.RemoveType <Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>(); options.OutputFormatters.RemoveType <Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter>(); }) .AddNewtonsoftJson(opts => { opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); opts.SerializerSettings.Converters.Add(new StringEnumConverter(new CamelCaseNamingStrategy())); }) .AddXmlSerializerFormatters(); var jwtOptions = new JwtTokenOptions(); var jwtOptionsRaw = Configuration.GetSection(JwtTokenOptions.JwtToken); jwtOptionsRaw.Bind(jwtOptions); var swaggerOptions = new MySwaggerOptions(); var swaggerOptionsRaw = Configuration.GetSection(MySwaggerOptions.SwaggerGen); swaggerOptionsRaw.Bind(swaggerOptions); services.AddDbContext <PaymentsDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString(PaymentDatabaseName))); services.AddAuthentication(options => { //options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; //options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; //options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme }) .AddJwtBearer(options => { options.SaveToken = true; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidAudience = jwtOptions.Issuer, ValidIssuer = jwtOptions.Issuer, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(IssuerSigningKeyString)) }; }); services.AddAuthorization(options => { options.AddPolicy(jwtOptions.Policy, policy => { policy.RequireClaim(jwtOptions.Claim.Type); }); }); #region BootstrapperForTokeIssuerToken var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(IssuerSigningKeyString)); var authClaims = new[] { new Claim(jwtOptions.Claim.Type, jwtOptions.Claim.Value) }; foreach (var audience in new[] { jwtOptions.Issuer }) { var token = new JwtSecurityToken( audience: audience, issuer: jwtOptions.Issuer, //expires: DateTime.Now.AddYears(3), claims: authClaims, signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); var tokenIssuer = new JwtSecurityTokenHandler().WriteToken(token); } #endregion services.AddSwaggerGen() .AddSwaggerGen(c => { c.SwaggerDoc(swaggerOptions.Version.ToLower(), new OpenApiInfo { Version = swaggerOptions.Version.ToUpper(), Title = swaggerOptions.Title, Description = swaggerOptions.Description, //Contact = new OpenApiContact() //{ // Name = "Swagger Codegen Contributors", // Url = new Uri("https://github.com/swagger-api/swagger-codegen"), // Email = string.Empty //} }); c.CustomSchemaIds(type => type.FullName); c.IncludeXmlComments($"{AppContext.BaseDirectory}{Path.DirectorySeparatorChar}{_hostingEnv.ApplicationName}.xml"); // Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..) // Use [ValidateModelState] on Actions to actually validate it in C# as well! c.OperationFilter <GeneratePathParamsValidationFilter>(); c.AddSecurityDefinition(jwtOptions.Scheme, new OpenApiSecurityScheme { Description = jwtOptions.Description, In = ParameterLocation.Header, Name = jwtOptions.Name, Type = SecuritySchemeType.Http, Scheme = jwtOptions.Scheme }); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = jwtOptions.Scheme }, Scheme = jwtOptions.SecurityType, Name = jwtOptions.Scheme, In = ParameterLocation.Header, }, new List <string>() } }); }); }