Implemented security functionality
Added data protection feature Migrated changes
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
using PostFundManagement.Domain.Api.Configuration;
|
||||
using PostFundManagement.Domain.Extensions;
|
||||
using PostFundManagement.Domain.Sdk;
|
||||
using PostFundManagement.Domain.Services;
|
||||
using PostFundManagement.Infrastructure.Database;
|
||||
|
||||
namespace PostFundManagement.Api.Extensions;
|
||||
|
||||
public static class Api
|
||||
{
|
||||
public static IServiceCollection AddSecurityApiSdk(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var configSection = configuration.GetSection(nameof(SecurityClientSettings));
|
||||
|
||||
var authOptions = new SecurityClientSettings();
|
||||
configSection.Bind(authOptions);
|
||||
|
||||
services.Configure<SecurityClientSettings>(configSection);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(authOptions.Authority))
|
||||
return services;
|
||||
|
||||
if (!authOptions.Authority.EndsWith("/", StringComparison.Ordinal)) authOptions.Authority += "/";
|
||||
|
||||
services.AddRefitClient<ISecurityConnectApi>()
|
||||
.ConfigureHttpClient(config =>
|
||||
{
|
||||
config.BaseAddress = new Uri(authOptions.Authority);
|
||||
config.Timeout = TimeSpan.FromSeconds(15);
|
||||
})
|
||||
.AddStandardResilienceHandler(options =>
|
||||
{
|
||||
options.Retry.MaxRetryAttempts = 3;
|
||||
options.Retry.Delay = TimeSpan.FromSeconds(1);
|
||||
options.Retry.BackoffType = Polly.DelayBackoffType.Exponential;
|
||||
});
|
||||
|
||||
services.AddScoped<TokenService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddWebSecurity(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var certString = configuration["DataProtection:Certificate"] ?? configuration["DataProtection__Certificate"];
|
||||
var certPassword = configuration["DataProtection:Password"] ?? configuration["DataProtection__Password"];
|
||||
|
||||
if (string.IsNullOrEmpty(certString))
|
||||
throw new InvalidOperationException("Data Protection Certificate configuration is missing.");
|
||||
|
||||
var certificate = X509CertificateLoader.LoadPkcs12(Convert.FromBase64String(certString), certPassword);
|
||||
|
||||
services.AddDataProtection().PersistKeysToDbContext<DataProtectionDbContext>()
|
||||
.ProtectKeysWithCertificate(certificate)
|
||||
.SetApplicationName("LiteCharmsApp");
|
||||
|
||||
services.Configure<DataProtectionOptions>(options => options.ApplicationDiscriminator = "LiteCharmsApp");
|
||||
|
||||
services.ConfigureCookieOidcSameSiteSupport();
|
||||
|
||||
var configSection = configuration.GetSection(nameof(SecuritySettings));
|
||||
|
||||
var authOptions = new SecuritySettings();
|
||||
configSection.Bind(authOptions);
|
||||
|
||||
services.Configure<SecuritySettings>(configSection);
|
||||
|
||||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
|
||||
})
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.Cookie.SameSite = SameSiteMode.Lax;
|
||||
options.Cookie.Name = "LiteCharmsApp.Session";
|
||||
})
|
||||
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
options.Authority = authOptions.Authority;
|
||||
options.ClientId = authOptions.ClientId;
|
||||
options.ClientSecret = authOptions.ClientSecret;
|
||||
options.ResponseType = "code";
|
||||
|
||||
options.SaveTokens = true;
|
||||
options.GetClaimsFromUserInfoEndpoint = true;
|
||||
options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.CorrelationCookie.SameSite = SameSiteMode.None;
|
||||
|
||||
options.NonceCookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.NonceCookie.SameSite = SameSiteMode.None;
|
||||
|
||||
options.ForwardSignOut = CookieAuthenticationDefaults.AuthenticationScheme;
|
||||
|
||||
options.Scope.Clear();
|
||||
options.Scope.Add("openid");
|
||||
options.Scope.Add("profile");
|
||||
options.Scope.Add("email");
|
||||
|
||||
options.Events = new OpenIdConnectEvents
|
||||
{
|
||||
OnRedirectToIdentityProviderForSignOut = context =>
|
||||
{
|
||||
var idToken = context.ProtocolMessage.IdTokenHint;
|
||||
|
||||
if (string.IsNullOrEmpty(idToken))
|
||||
{
|
||||
var tokens = context.Properties.GetTokens();
|
||||
var idTokenItem = tokens.FirstOrDefault(t => string.Equals(t.Name, "id_token", StringComparison.Ordinal));
|
||||
|
||||
if (idTokenItem != null) context.ProtocolMessage.IdTokenHint = idTokenItem.Value;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
services.AddCascadingAuthenticationState();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -13,4 +13,19 @@
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.16.20" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Global Usings -->
|
||||
<ItemGroup>
|
||||
<Using Include="System.Security.Cryptography.X509Certificates" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.Cookies" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
<Using Include="Microsoft.AspNetCore.DataProtection" />
|
||||
<Using Include="Refit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PostFundManagement.Domain\PostFundManagement.Domain.csproj" />
|
||||
<ProjectReference Include="..\PostFundManagement.Infrastructure\PostFundManagement.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -2,13 +2,10 @@ using Scalar.AspNetCore;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapScalarApiReference(options =>
|
||||
@@ -16,33 +13,10 @@ if (app.Environment.IsDevelopment())
|
||||
options.WithTitle("Post-fund Management API")
|
||||
.WithTheme(ScalarTheme.BluePlanet);
|
||||
});
|
||||
|
||||
app.MapOpenApi();
|
||||
}
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
var summaries = new[]
|
||||
{
|
||||
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
|
||||
};
|
||||
|
||||
app.MapGet("/weatherforecast", () =>
|
||||
{
|
||||
var forecast = Enumerable.Range(1, 5).Select(index =>
|
||||
new WeatherForecast
|
||||
(
|
||||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
|
||||
Random.Shared.Next(-20, 55),
|
||||
summaries[Random.Shared.Next(summaries.Length)]
|
||||
))
|
||||
.ToArray();
|
||||
return forecast;
|
||||
})
|
||||
.WithName("GetWeatherForecast");
|
||||
|
||||
app.Run();
|
||||
|
||||
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
|
||||
{
|
||||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user