Implemented security functionality
Added data protection feature Migrated changes
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
using static PostFundManagement.Domain.Extensions.Timezones;
|
||||
|
||||
namespace PostFundManagement.Domain.Abstractions;
|
||||
|
||||
public abstract class EventBase
|
||||
{
|
||||
public Guid Id { get; set; } = Guid.CreateVersion7();
|
||||
|
||||
public DateTimeOffset EnqueueAt { get; set; } = (DateTimeOffset)SouthAfricanTimeZone.UtcNow();
|
||||
|
||||
public string CorrelationId { get; set; } = Guid.CreateVersion7().ToString();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace PostFundManagement.Domain.Abstractions;
|
||||
|
||||
public interface IEvent : INotification
|
||||
{
|
||||
Guid Id { get; set; }
|
||||
|
||||
string Name { get; set; }
|
||||
|
||||
DateTimeOffset EnqueueAt { get; set; }
|
||||
|
||||
string CorrelationId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace PostFundManagement.Domain.Abstractions;
|
||||
|
||||
public interface IJobOrchestrator
|
||||
{
|
||||
ValueTask SendAsync<TNotification>(TNotification notification, CancellationToken cancellationToken = default)
|
||||
where TNotification : IEvent;
|
||||
|
||||
ValueTask ScheduleAsync<TNotification>(TNotification notification, string cronExpression, CancellationToken cancellationToken = default)
|
||||
where TNotification : IEvent;
|
||||
|
||||
ValueTask<bool> InterruptAsync(string eventName, string? correlationId = null, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace PostFundManagement.Domain.Api;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||
public sealed class ApiVersionTargetAttribute(int majorVersion) : Attribute
|
||||
{
|
||||
public int MajorVersion { get; } = majorVersion;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace PostFundManagement.Domain.Api.Configuration;
|
||||
|
||||
public sealed class SecurityClientSettings
|
||||
{
|
||||
public string? Authority { get; set; }
|
||||
|
||||
public string? GrantType { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
|
||||
public string? ClientSecret { get; set; }
|
||||
|
||||
public string? Scope { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace PostFundManagement.Domain.Api.Configuration;
|
||||
|
||||
public sealed class SecuritySettings
|
||||
{
|
||||
public string? Authority { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
|
||||
public string? ClientSecret { get; set; }
|
||||
|
||||
public string? Audience { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace PostFundManagement.Domain.Api.Models;
|
||||
|
||||
public sealed class TokenErrorResponse
|
||||
{
|
||||
[JsonPropertyName("error")]
|
||||
public string? Error { get; set; }
|
||||
|
||||
[JsonPropertyName("error_description")]
|
||||
public string? ErrorDescription { get; set; }
|
||||
|
||||
[JsonPropertyName("error_uri")]
|
||||
public string? ErrorUri { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace PostFundManagement.Domain.Api.Models;
|
||||
|
||||
public sealed class TokenRequest
|
||||
{
|
||||
[JsonPropertyName("grant_type")]
|
||||
[AliasAs("grant_type")]
|
||||
public string? GrantType { get; set; }
|
||||
|
||||
[JsonPropertyName("client_id")]
|
||||
[AliasAs("client_id")]
|
||||
public string? ClientId { get; set; }
|
||||
|
||||
[JsonPropertyName("client_secret")]
|
||||
[AliasAs("client_secret")]
|
||||
public string? ClientSecret { get; set; }
|
||||
|
||||
[JsonPropertyName("scope")]
|
||||
[AliasAs("scope")]
|
||||
public string? Scope { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace PostFundManagement.Domain.Api.Models;
|
||||
|
||||
public sealed class TokenResponse
|
||||
{
|
||||
[JsonPropertyName("access_token")]
|
||||
public string? AccessToken { get; set; }
|
||||
|
||||
[JsonPropertyName("expires_in")]
|
||||
public int ExpiresIn { get; set; }
|
||||
|
||||
[JsonPropertyName("token_type")]
|
||||
public string? TokenType { get; set; }
|
||||
|
||||
[JsonPropertyName("scope")]
|
||||
public string? Scope { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace PostFundManagement.Domain.Api;
|
||||
|
||||
public sealed class OpenApiBearerSecuritySchemeTransformer : IOpenApiDocumentTransformer
|
||||
{
|
||||
public async Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
var bearerScheme = new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.Http,
|
||||
Scheme = "bearer",
|
||||
Description = "JWT Authorization header using the Bearer scheme",
|
||||
};
|
||||
|
||||
document.AddComponent("Bearer", bearerScheme);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
using PostFundManagement.Domain.Abstractions;
|
||||
using PostFundManagement.Domain.Api;
|
||||
using PostFundManagement.Domain.Api.Configuration;
|
||||
|
||||
namespace PostFundManagement.Domain.Extensions;
|
||||
|
||||
public static class Api
|
||||
{
|
||||
public static void ConfigureCookieOidcSameSiteSupport(this IServiceCollection services) =>
|
||||
services.Configure<CookiePolicyOptions>(options =>
|
||||
{
|
||||
options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
|
||||
options.OnAppendCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
|
||||
options.OnDeleteCookie = cookieContext => CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
|
||||
});
|
||||
|
||||
public static void CheckSameSite(HttpContext httpContext, CookieOptions options)
|
||||
{
|
||||
if (options.SameSite == SameSiteMode.None)
|
||||
{
|
||||
bool isSecure = httpContext.Request.IsHttps;
|
||||
|
||||
if (!isSecure && httpContext.Request.Headers.TryGetValue("X-Forwarded-Proto", out var proto))
|
||||
isSecure = string.Equals(proto, "https", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isSecure && httpContext.Request.Headers.TryGetValue("Forwarded", out var forwarded))
|
||||
isSecure = forwarded.ToString().Contains("proto=https", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (!isSecure) options.SameSite = SameSiteMode.Unspecified;
|
||||
}
|
||||
}
|
||||
|
||||
public static IServiceCollection AddLiteCharmsApiSecurity(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var configSection = configuration.GetSection(nameof(SecuritySettings));
|
||||
|
||||
var authOptions = new SecuritySettings();
|
||||
configSection.Bind(authOptions);
|
||||
|
||||
services.Configure<SecuritySettings>(configSection);
|
||||
|
||||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.Authority = authOptions.Authority;
|
||||
options.Audience = authOptions.Audience;
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = authOptions.Authority,
|
||||
ValidateAudience = true,
|
||||
ValidateIssuer = true,
|
||||
};
|
||||
});
|
||||
|
||||
services.AddAuthorization();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static WebApplication AddSecurityEndpoints(this WebApplication app)
|
||||
{
|
||||
app.MapGet("/login", async (HttpContext context, string redirectUri = "/") =>
|
||||
{
|
||||
await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties
|
||||
{
|
||||
RedirectUri = redirectUri,
|
||||
});
|
||||
});
|
||||
|
||||
app.MapGet("/logout", async (HttpContext context, string? redirectUri = null) =>
|
||||
{
|
||||
var idToken = await context.GetTokenAsync("id_token");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(redirectUri))
|
||||
{
|
||||
var host = context.Request.Host.ToUriComponent();
|
||||
redirectUri = $"https://{host}/";
|
||||
}
|
||||
|
||||
var authProperties = new AuthenticationProperties { RedirectUri = redirectUri, };
|
||||
|
||||
if (!string.IsNullOrEmpty(idToken))
|
||||
authProperties.Parameters.Add("id_token_hint", idToken);
|
||||
|
||||
await context.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme, authProperties);
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddApiServices(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
services.AddHttpClient();
|
||||
|
||||
services.AddApiVersioning(options =>
|
||||
{
|
||||
options.ReportApiVersions = true;
|
||||
options.AssumeDefaultVersionWhenUnspecified = true;
|
||||
options.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(),
|
||||
new QueryStringApiVersionReader("version"),
|
||||
new QueryStringApiVersionReader("version"),
|
||||
new MediaTypeApiVersionReader("version"));
|
||||
})
|
||||
.AddApiExplorer(options =>
|
||||
{
|
||||
options.GroupNameFormat = "'v'VVV";
|
||||
options.SubstituteApiVersionInUrl = true;
|
||||
});
|
||||
|
||||
var urls = configuration["ASPNETCORE_URLS"] ?? configuration["Urls"];
|
||||
var healthUrl = "http://localhost:8080/health";
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(urls))
|
||||
{
|
||||
string firstUrl = urls.Split(';').FirstOrDefault(s => s.Contains("http://", StringComparison.InvariantCultureIgnoreCase))!
|
||||
.Replace("0.0.0.0", "localhost")
|
||||
.Replace("*", "localhost")
|
||||
.Replace("+", "localhost");
|
||||
|
||||
healthUrl = $"{firstUrl.TrimEnd('/')}/health";
|
||||
}
|
||||
|
||||
services.AddHealthChecksUI(setup =>
|
||||
{
|
||||
setup.SetNotifyUnHealthyOneTimeUntilChange();
|
||||
setup.AddHealthCheckEndpoint("primary, heal", healthUrl);
|
||||
setup.SetHeaderText("Midrand Books");
|
||||
})
|
||||
.AddInMemoryStorage();
|
||||
|
||||
services.AddOutputCache(options =>
|
||||
{
|
||||
options.AddBasePolicy(builder => builder.Cache());
|
||||
options.DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10);
|
||||
});
|
||||
|
||||
services.AddOpenApi(options => options.AddDocumentTransformer<OpenApiBearerSecuritySchemeTransformer>());
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IApplicationBuilder MapEndpoints(this WebApplication app, IDictionary<int, RouteGroupBuilder> versionGroups)
|
||||
{
|
||||
var endpoints = app.Services.GetRequiredService<IEnumerable<IEndpoint>>();
|
||||
|
||||
foreach (var endpoint in endpoints)
|
||||
{
|
||||
var versionAttributes = endpoint.GetType().GetCustomAttributes<ApiVersionTargetAttribute>().ToList();
|
||||
|
||||
if (versionAttributes.Count != 0)
|
||||
{
|
||||
foreach (var attr in versionAttributes)
|
||||
if (versionGroups.TryGetValue(attr.MajorVersion, out var targetGroup))
|
||||
endpoint.Map(targetGroup);
|
||||
}
|
||||
else
|
||||
endpoint.Map(app);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
public static IServiceCollection AddEndpoints(this IServiceCollection services, Assembly assembly)
|
||||
{
|
||||
ServiceDescriptor[] discriptors = [.. assembly.DefinedTypes
|
||||
.Where(t => t is { IsInterface: false, IsAbstract: false })
|
||||
.Where(t => t.IsAssignableTo(typeof(IEndpoint)))
|
||||
.Select(t => ServiceDescriptor.Transient(typeof(IEndpoint), t))];
|
||||
|
||||
services.TryAddEnumerable(discriptors);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
public static string ToEndpointName(this Type target, string? annotation = "") =>
|
||||
$"{target.Name.Replace("Endpoint", string.Empty)}{annotation}".ToLower(CultureInfo.CurrentCulture);
|
||||
}
|
||||
@@ -21,7 +21,6 @@ public static class Mappers
|
||||
UpdatedAt = entity.UpdatedAt,
|
||||
UpdatedBy = entity.UpdatedBy
|
||||
};
|
||||
|
||||
|
||||
public static AuditLog Map(this Entities.AuditLog entity) => new()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace PostFundManagement.Domain.Extensions;
|
||||
|
||||
public static class Timezones
|
||||
{
|
||||
public static TimeZoneInfo SouthAfricanTimeZone => TimeZoneInfo.FindSystemTimeZoneById("South Africa Standard Time");
|
||||
|
||||
public static string? LocaliseDateTime(this DateTime dateTime, TimeSpan offset) => offset.Hours > 0
|
||||
? $"{dateTime:yyyy-MM-ddTHH:mm:ss.fff}+{offset.Hours:00}:{offset.Minutes:00}"
|
||||
: $"{dateTime:yyyy-MM-ddTHH:mm:ss.fff}{offset.Hours:00}:{offset.Minutes:00}";
|
||||
|
||||
public static string? LocaliseDateTimeOffset(this DateTimeOffset dateTime, TimeSpan offset) => LocaliseDateTime(dateTime.DateTime, offset);
|
||||
|
||||
public static DateTimeOffset ToDateTimeWithTimeZone(this DateTime source, TimeZoneInfo? timezone = null)
|
||||
{
|
||||
DateTime sourceDateAdjusted = source.Kind != DateTimeKind.Utc
|
||||
? new(source.Ticks, DateTimeKind.Utc)
|
||||
: source;
|
||||
|
||||
var localised = timezone is null
|
||||
? new DateTimeOffset(sourceDateAdjusted.Ticks, SouthAfricanTimeZone.BaseUtcOffset).LocaliseDateTimeOffset(SouthAfricanTimeZone.BaseUtcOffset)
|
||||
: new DateTimeOffset(sourceDateAdjusted.Ticks, timezone!.BaseUtcOffset).LocaliseDateTimeOffset(timezone.BaseUtcOffset);
|
||||
|
||||
return DateTimeOffset.Parse(localised!, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
public static DateTime UtcNow(this TimeZoneInfo timezone) => ToDateTimeWithTimeZone(DateTime.Now, timezone).UtcDateTime;
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
<PackageReference Include="Polly" Version="8.7.0" />
|
||||
<PackageReference Include="Polly.Extensions" Version="8.7.0" />
|
||||
|
||||
<Using Include="AccessTokenClient" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" />
|
||||
<Using Include="Microsoft.AspNetCore.Authentication.Cookies" />
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace PostFundManagement.Domain.Sdk;
|
||||
|
||||
public interface ISecurityConnectApi
|
||||
{
|
||||
[Post("/connect/token")]
|
||||
ValueTask<HttpResponseMessage> GetToken([Body(BodySerializationMethod.UrlEncoded)] Api.Models.TokenRequest request, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using PostFundManagement.Domain.Api.Configuration;
|
||||
using PostFundManagement.Domain.Api.Models;
|
||||
using PostFundManagement.Domain.Sdk;
|
||||
|
||||
namespace PostFundManagement.Domain.Services;
|
||||
|
||||
public sealed class TokenService(ISecurityConnectApi connectApi, IOptions<SecurityClientSettings> clientOptions)
|
||||
{
|
||||
private readonly SecurityClientSettings clientSettings = clientOptions.Value;
|
||||
|
||||
public async Task<Result<Api.Models.TokenResponse>> GenerateAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new Api.Models.TokenRequest
|
||||
{
|
||||
ClientId = clientSettings.ClientId,
|
||||
ClientSecret = clientSettings.ClientSecret,
|
||||
GrantType = clientSettings.GrantType,
|
||||
Scope = clientSettings.Scope,
|
||||
};
|
||||
|
||||
using var response = await connectApi.GetToken(request, cancellationToken);
|
||||
|
||||
var contentRaw = await response.Content.ReadAsStringAsync(cancellationToken);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(contentRaw))
|
||||
return Result.Fail(new Error($"The authentication endpoint returned an empty payload. Status code: {response.StatusCode}"));
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var tokenResponse = JsonSerializer.Deserialize<Api.Models.TokenResponse>(contentRaw);
|
||||
|
||||
return !string.IsNullOrWhiteSpace(tokenResponse?.AccessToken)
|
||||
? Result.Ok(tokenResponse)
|
||||
: Result.Fail<Api.Models.TokenResponse>(new Error("Authentication succeeded, but no access token was found in the response payload."));
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var errorResult = JsonSerializer.Deserialize<TokenErrorResponse>(contentRaw);
|
||||
|
||||
if (errorResult != null)
|
||||
{
|
||||
string summary = $"{errorResult.Error}: {errorResult.ErrorDescription}";
|
||||
|
||||
return Result.Fail(new Error(summary));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
return Result.Fail(new Error($"Authentication failed: {contentRaw}"));
|
||||
}
|
||||
|
||||
return Result.Fail(new Error($"Authentication failed with status code: {response.StatusCode}"));
|
||||
}
|
||||
catch (OperationCanceledException ex)
|
||||
{
|
||||
return Result.Fail(new Error("The token generation request was canceled.").CausedBy(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Result.Fail(new Error(ex.Message).CausedBy(ex));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user