2021-12-15 16:05:50 +01:00

67 lines
1.9 KiB
C#

using HackerNet.Infrastructure.AspNet;
using HackerNet.Infrastructure.Repositories.EntityFramework;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
var tokenValidation = builder.Configuration
.GetSection("TokenValidation")
.Get<TokenValidation>();
builder.Services.AddSingleton(tokenValidation);
builder.Services.AddHackerNetServicesEntityFramework(builder.Configuration);
builder.Services.AddControllers();
builder.Services
.AddIdentityCore<IdentityUser>(o =>
{
o.Password.RequireNonAlphanumeric = false;
})
.AddRoles<IdentityRole>()
.AddSignInManager()
.AddEntityFrameworkStores<HackerContext>();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(o =>
{
o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudience = tokenValidation.Audience,
ValidIssuer = tokenValidation.Issuer,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(tokenValidation.Key)),
};
});
builder.Services.AddOpenApiDocument(d =>
{
d.Title = "HackerNet API";
});
var app = builder.Build();
app.MigrateDatabase();
app.UseOpenApi();
app.UseSwaggerUi3();
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/", () => "Hello World!");
app.MapControllers();
app.Run();
public class TokenValidation
{
public string Audience { get; set; }
public string Issuer { get; set; }
public string Key { get; set; }
}