using System.Linq; using System.Text; using HN.Infrastructure; using HN.Infrastructure.Identity; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using NSwag; using NSwag.Generation.Processors.Security; namespace Api { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddHN(Configuration).ResolveConnectedUserWith(); services.AddHttpContextAccessor(); // Permet d'avoir des routes en lowercase services.Configure(options => { options.LowercaseUrls = true; options.LowercaseQueryStrings = true; }); // Ajout de l'authentification var tokenParams = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["JwtIssuer"], ValidAudience = Configuration["JwtAudience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSecurityKey"])) }; services.AddSingleton(tokenParams); services.AddIdentityCore() .AddRoles() .AddEntityFrameworkStores() .AddSignInManager(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(o => { o.TokenValidationParameters = tokenParams; }); services.AddControllers(o => { o.Filters.Add(new AuthorizeFilter()); }); services.AddSwaggerDocument(d => { // cf. https://github.com/RicoSuter/NSwag/wiki/AspNetCore-Middleware#enable-authentication-in-generator-and-swagger-ui // Ajoute un type de sécurité à tout le document d.AddSecurity("JWT", Enumerable.Empty(), new OpenApiSecurityScheme() { Type = OpenApiSecuritySchemeType.ApiKey, Name = "Authorization", In = OpenApiSecurityApiKeyLocation.Header, Description = "Type into the textbox: Bearer {your JWT token}." }); // d.DocumentProcessors.Add(new SecurityDefinitionAppender("JWT", new OpenApiSecurityScheme // { // Type = OpenApiSecuritySchemeType.ApiKey, // Name = "Authorization", // In = OpenApiSecurityApiKeyLocation.Header, // Description = "Type into the textbox: Bearer {your JWT token}." // })); // Permet la génération des info de sécurité par réflexion (attribut Authorize) // Fonctionne mal avec les filtres par défaut ... d.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("JWT")); d.PostProcess = od => { od.Info.Title = "Hacker news like API in .Net"; }; d.SchemaType = NJsonSchema.SchemaType.OpenApi3; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseOpenApi(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwaggerUi3(); } app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); }); } } }