hn-dotnet/Apps/Api/Startup.cs

133 lines
4.2 KiB
C#

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<HttpExecutingUserProvider>();
services.AddHttpContextAccessor();
// Permet d'avoir des routes en lowercase
services.Configure<RouteOptions>(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<User>()
.AddRoles<Role>()
.AddEntityFrameworkStores<HNDbContext>()
.AddSignInManager();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = tokenParams;
});
services.AddControllers(o =>
{
o.Filters.Add(new AuthorizeFilter()); // Ou MapControllers().RequireAuthentication()
});
services.AddOpenApiDocument(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<string>(), 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";
};
});
}
// 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!");
});
});
}
}
}