Migration to EF and starting to add Identity #11

Merged
jtom38 merged 16 commits from features/ef-identity-migration into main 2023-07-09 22:19:01 -07:00
Showing only changes of commit f081a59229 - Show all commits

View File

@ -1,14 +1,24 @@
using System.Text;
using Hangfire; using Hangfire;
using Hangfire.MemoryStorage; using Hangfire.MemoryStorage;
using HealthChecks.UI.Client; using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Newsbot.Collector.Api; using Newsbot.Collector.Api;
using Newsbot.Collector.Api.Authentication; using Newsbot.Collector.Api.Authentication;
using Newsbot.Collector.Api.Services;
using Newsbot.Collector.Database; using Newsbot.Collector.Database;
using Newsbot.Collector.Database.Repositories;
using Newsbot.Collector.Domain.Consts; using Newsbot.Collector.Domain.Consts;
using Newsbot.Collector.Domain.Entities;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Domain.Models; using Newsbot.Collector.Domain.Models;
using Newsbot.Collector.Domain.Models.Config; using Newsbot.Collector.Domain.Models.Config;
using Newsbot.Collector.Domain.Models.Config.Sources;
using Serilog; using Serilog;
using Serilog.Events; using Serilog.Events;
using ILogger = Serilog.ILogger; using ILogger = Serilog.ILogger;
@ -23,30 +33,76 @@ var config = GetConfiguration();
builder.Configuration.AddConfiguration(config); builder.Configuration.AddConfiguration(config);
Log.Logger = GetLogger(config); Log.Logger = GetLogger(config);
Log.Information("Starting up"); Log.Information("Starting up");
// configure Entity Framework
var dbconn = config.GetConnectionString("Database");
builder.Services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
builder.Services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>();
builder.Services.AddScoped<IArticlesRepository, ArticlesTable>();
builder.Services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
builder.Services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
builder.Services.AddScoped<IIconsRepository, IconsTable>();
builder.Services.AddScoped<ISourcesRepository, SourcesTable>();
builder.Services.AddScoped<ISubscriptionRepository, SubscriptionsTable>();
// Configure Identity
builder.Services.AddScoped<IIdentityService, IdentityService>();
// Configure Hangfire // Configure Hangfire
builder.Services.AddHangfire(f => f.UseMemoryStorage()); builder.Services.AddHangfire(f => f.UseMemoryStorage());
builder.Services.AddHangfireServer(); builder.Services.AddHangfireServer();
GlobalConfiguration.Configuration.UseSerilogLogProvider(); GlobalConfiguration.Configuration.UseSerilogLogProvider();
// Add Health Checks
builder.Services.AddHealthChecks() builder.Services.AddHealthChecks()
.AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? ""); .AddNpgSql(config.GetValue<string>(ConfigConnectionStringConst.Database) ?? "");
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings")); builder.Services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings"));
builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings)); builder.Services.Configure<ConfigSectionConnectionStrings>(config.GetSection(ConfigSectionsConst.ConnectionStrings));
builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss)); builder.Services.Configure<ConfigSectionRssModel>(config.GetSection(ConfigSectionsConst.Rss));
builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube)); builder.Services.Configure<ConfigSectionYoutubeModel>(config.GetSection(ConfigSectionsConst.Youtube));
//builder.Services.Configure< //builder.Services.Configure<
// Configure JWT for auth
var jwtSettings = new JwtSettings();
config.Bind(nameof(jwtSettings), jwtSettings);
builder.Services.AddSingleton(jwtSettings);
builder.Services.AddAuthentication(x =>
{
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.Secret ?? "")),
ValidateIssuer = false,
ValidateAudience = false,
RequireExpirationTime = false,
ValidateLifetime = true
};
});
builder.Services.AddSwaggerGen(cfg => builder.Services.AddSwaggerGen(cfg =>
{ {
cfg.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme cfg.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{ {
Description = "The API key to access the API", Description = "The API key to access the API",
@ -56,23 +112,45 @@ builder.Services.AddSwaggerGen(cfg =>
Scheme = "ApiKeyScheme" Scheme = "ApiKeyScheme"
}); });
var scheme = new OpenApiSecurityScheme cfg.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{ {
Reference = new OpenApiReference Description = "JWT Authorization Header using the bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
cfg.AddSecurityRequirement(new OpenApiSecurityRequirement
{
//{
// new OpenApiSecurityScheme
// {
// Reference = new OpenApiReference
// {
// Type = ReferenceType.SecurityScheme,
// Id = "ApiKey"
// },
// In = ParameterLocation.Header
// },
// new List<string>()
//},
{ {
Type = ReferenceType.SecurityScheme, new OpenApiSecurityScheme
Id = "ApiKey" {
}, Reference = new OpenApiReference
In = ParameterLocation.Header {
}; Type = ReferenceType.SecurityScheme,
var requirement = new OpenApiSecurityRequirement Id = "Bearer"
{ },
{ scheme, new List<string>() } Scheme = "oauth2",
}; Name = "Bearer",
cfg.AddSecurityRequirement(requirement); In = ParameterLocation.Header
},
new List<string>()
}
});
}); });
builder.Services.AddDbContext<DatabaseContext>();
var app = builder.Build(); var app = builder.Build();
@ -88,9 +166,10 @@ app.UseHttpsRedirection();
app.UseHangfireDashboard(); app.UseHangfireDashboard();
BackgroundJobs.SetupRecurringJobs(config); BackgroundJobs.SetupRecurringJobs(config);
app.UseAuthorization(); //app.UseAuthorization();
app.UseAuthentication();
app.UseMiddleware<ApiKeyAuthAuthentication>(); //app.UseMiddleware<ApiKeyAuthAuthentication>();
app.MapHealthChecks("/health", new HealthCheckOptions app.MapHealthChecks("/health", new HealthCheckOptions
{ {