Cleanup and bugfix
This commit is contained in:
@@ -1,70 +0,0 @@
|
||||
using MaxInventory.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MaxInventory.Authentication.Core
|
||||
{
|
||||
public sealed class AdminCookieValidationEvents : CookieAuthenticationEvents
|
||||
{
|
||||
private static readonly string[] GroupClaimTypes =
|
||||
{
|
||||
"groups",
|
||||
"group",
|
||||
"role",
|
||||
"roles",
|
||||
ClaimTypes.GroupSid,
|
||||
ClaimTypes.Role,
|
||||
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
|
||||
"http://schemas.xmlsoap.org/claims/Group"
|
||||
};
|
||||
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public AdminCookieValidationEvents(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
|
||||
{
|
||||
if (context.Principal?.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return;
|
||||
}
|
||||
|
||||
var path = context.HttpContext.Request.Path;
|
||||
if (!path.StartsWithSegments("/Admin", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty)
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
|
||||
|
||||
var principalGroups = identity.Claims
|
||||
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(c => c.Value);
|
||||
|
||||
var isAdmin = configuredGroups.Length > 0 &&
|
||||
principalGroups.Any(group =>
|
||||
configuredGroups.Contains(group, StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
if (!isAdmin)
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
<Solution>
|
||||
<Project Path="MaxInventory.Authentication/MaxInventory.Authentication.csproj" Id="c1189b9b-4806-4281-ad95-6c50f1199d25" />
|
||||
<Project Path="src/MaxInventory.Authentication/MaxInventory.Authentication.csproj" Id="c1189b9b-4806-4281-ad95-6c50f1199d25" />
|
||||
<Project Path="src/MaxInventory.Core/MaxInventory.Core.csproj" Id="811e1f0d-a0d1-449a-8787-6a54c382515c" />
|
||||
<Project Path="src/MaxInventory.Infrastructure/MaxInventory.Infrastructure.csproj" Id="c97d502d-a07f-41e9-a6c7-a8254d9c3c70" />
|
||||
<Project Path="src/MaxInventory.Web/MaxInventory.Web.csproj" />
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using MaxInventory.Authentication.Core;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MaxInventory.Authentication.Abstractions
|
||||
{
|
||||
public interface IPrincipalAccessEvaluator
|
||||
{
|
||||
Task<PrincipalAccess> EvaluateAsync(ClaimsPrincipal principal, CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using MaxInventory.Authentication.Abstractions;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MaxInventory.Authentication.Core
|
||||
{
|
||||
public sealed class AdminCookieValidationEvents : CookieAuthenticationEvents
|
||||
{
|
||||
private readonly IPrincipalAccessEvaluator _principalAccessEvaluator;
|
||||
|
||||
public AdminCookieValidationEvents(IPrincipalAccessEvaluator principalAccessEvaluator)
|
||||
{
|
||||
_principalAccessEvaluator = principalAccessEvaluator;
|
||||
}
|
||||
|
||||
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
|
||||
{
|
||||
if (context.Principal?.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
return;
|
||||
}
|
||||
|
||||
var path = context.HttpContext.Request.Path;
|
||||
if (!path.StartsWithSegments("/Admin", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var access = await _principalAccessEvaluator.EvaluateAsync(context.Principal);
|
||||
if (!access.CanDelete)
|
||||
{
|
||||
context.RejectPrincipal();
|
||||
await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace MaxInventory.Authentication.Core
|
||||
{
|
||||
public sealed record PrincipalAccess(bool IsAuthenticated, bool CanView, bool CanEdit, bool CanDelete);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using MaxInventory.Authentication.Abstractions;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MaxInventory.Authentication.Core
|
||||
{
|
||||
public sealed class PrincipalAccessEvaluator : IPrincipalAccessEvaluator
|
||||
{
|
||||
private static readonly string[] GroupClaimTypes =
|
||||
{
|
||||
"groups",
|
||||
"group",
|
||||
"role",
|
||||
"roles",
|
||||
ClaimTypes.GroupSid,
|
||||
ClaimTypes.Role,
|
||||
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
|
||||
"http://schemas.xmlsoap.org/claims/Group"
|
||||
};
|
||||
|
||||
private readonly IAdminGroupSource _adminGroupSource;
|
||||
|
||||
public PrincipalAccessEvaluator(IAdminGroupSource adminGroupSource)
|
||||
{
|
||||
_adminGroupSource = adminGroupSource;
|
||||
}
|
||||
|
||||
public async Task<PrincipalAccess> EvaluateAsync(ClaimsPrincipal principal, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
return new PrincipalAccess(false, false, false, false);
|
||||
}
|
||||
|
||||
var principalGroups = identity.Claims
|
||||
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(c => c.Value);
|
||||
|
||||
var groupSet = new HashSet<string>(principalGroups, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var isAdmin = principal.IsInRole(AuthRoles.Admin) ||
|
||||
IsInConfiguredGroup(groupSet, await _adminGroupSource.GetAdminGroupsAsync(cancellationToken));
|
||||
var canEdit = isAdmin ||
|
||||
principal.IsInRole(AuthRoles.EditAdd) ||
|
||||
IsInConfiguredGroup(groupSet, await _adminGroupSource.GetEditGroupsAsync(cancellationToken));
|
||||
var canView = canEdit ||
|
||||
principal.IsInRole(AuthRoles.View) ||
|
||||
IsInConfiguredGroup(groupSet, await _adminGroupSource.GetViewGroupsAsync(cancellationToken));
|
||||
|
||||
return new PrincipalAccess(true, canView, canEdit, isAdmin);
|
||||
}
|
||||
|
||||
private static bool IsInConfiguredGroup(HashSet<string> principalGroups, IReadOnlyCollection<string> configuredGroups)
|
||||
{
|
||||
if (configuredGroups.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return configuredGroups.Any(principalGroups.Contains);
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -1,4 +1,4 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
@@ -22,6 +22,7 @@ namespace MaxInventory.Authentication.Extensions
|
||||
{
|
||||
services.TryAddSingleton<IIdentityContextFactory, IdentityContextFactory>();
|
||||
services.TryAddSingleton<IAdminGroupSource, ConfiguredAdminGroupSource>();
|
||||
services.TryAddScoped<IPrincipalAccessEvaluator, PrincipalAccessEvaluator>();
|
||||
services.AddScoped<IClaimsTransformation, AdminRoleClaimsTransformation>();
|
||||
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, AdfsWsFedAuthProvider>());
|
||||
@@ -78,3 +79,4 @@ namespace MaxInventory.Authentication.Extensions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/// <summary>
|
||||
/// Base URL for the inventory API.
|
||||
/// </summary>
|
||||
public string BaseUrl { get; set; } = "https://directauth.max.gov/inventory";
|
||||
public string? BaseUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// HTTP request timeout in seconds. Default is 30.
|
||||
|
||||
@@ -3,35 +3,17 @@
|
||||
/// <summary>
|
||||
/// Configuration settings for client certificate authentication.
|
||||
/// Bound from the "Certificate" section of appsettings.json.
|
||||
/// Supports two modes: Windows certificate store lookup (by friendly name)
|
||||
/// or file-based PFX loading (for Docket/Linux environments).
|
||||
/// Uses a mounted PFX file path, typically sourced from a Kubernetes secret volume.
|
||||
/// </summary>
|
||||
public sealed class CertificateSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// When true, loads certificate from a PFX file (FilePath + Password).
|
||||
/// When false, searches the Windows machine certificate store by FriendlyName.
|
||||
/// Path to the mounted PFX certificate file.
|
||||
/// </summary>
|
||||
public bool UseFile { get; set; } = false;
|
||||
|
||||
///<summary>Friendly name of the certificate in the Windows machine store.
|
||||
///Used when UseFile is false.
|
||||
/// </summary>
|
||||
public string? FriendlyName { get; set; } = "alleman_j inventory.max.gov client";
|
||||
|
||||
///<summary>
|
||||
///Certificate thumbprint in the windows machine store.
|
||||
///Used as a fallback when UseFile is false and FriendlyName lookup does not find a certificate.
|
||||
/// </summary>
|
||||
public string? Thumbprint { get; set; }
|
||||
public string? Path { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Path to the PFX certificate file. Used when UseFile is true.
|
||||
/// </summary>
|
||||
public string? FilePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Password for the PFC certificate file. Used when UseFile is true.
|
||||
/// Password for the PFX certificate file when one is required.
|
||||
/// </summary>
|
||||
public string? Password { get; set; }
|
||||
}
|
||||
|
||||
@@ -11,12 +11,12 @@ namespace MaxInventory.Infrastructure.Certificates
|
||||
public sealed class FileCertificateProvider : ICertificateProvider
|
||||
{
|
||||
private readonly string _filePath;
|
||||
private readonly string _password;
|
||||
private readonly string? _password;
|
||||
|
||||
public FileCertificateProvider(string filePath, string password)
|
||||
public FileCertificateProvider(string filePath, string? password)
|
||||
{
|
||||
_filePath = filePath ?? throw new ArgumentNullException(nameof(filePath));
|
||||
_password = password ?? throw new ArgumentNullException(nameof(password));
|
||||
_password = password;
|
||||
}
|
||||
|
||||
///<inheritdoc/>
|
||||
@@ -29,11 +29,15 @@ namespace MaxInventory.Infrastructure.Certificates
|
||||
$"is mounted or copied to the expected location.", _filePath);
|
||||
}
|
||||
|
||||
return new X509Certificate2(
|
||||
_filePath,
|
||||
_password,
|
||||
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet
|
||||
);
|
||||
return string.IsNullOrWhiteSpace(_password)
|
||||
? new X509Certificate2(
|
||||
_filePath,
|
||||
(string?)null,
|
||||
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet)
|
||||
: new X509Certificate2(
|
||||
_filePath,
|
||||
_password,
|
||||
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ using MaxInventory.Core.Services;
|
||||
using MaxInventory.Core.Settings;
|
||||
using MaxInventory.Infrastructure.Certificates;
|
||||
using MaxInventory.Infrastructure.Http;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace MaxInventory.Infrastructure.Extensions
|
||||
{
|
||||
@@ -26,41 +25,28 @@ namespace MaxInventory.Infrastructure.Extensions
|
||||
// Bind settings from configuration
|
||||
var apiSettings = new ApiSettings();
|
||||
configuration.GetSection("Api").Bind(apiSettings);
|
||||
if (string.IsNullOrWhiteSpace(apiSettings.BaseUrl))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Api.BaseUrl must be provided via configuration or Kubernetes secret.");
|
||||
}
|
||||
services.AddSingleton(apiSettings);
|
||||
|
||||
var certSettings = new CertificateSettings();
|
||||
configuration.GetSection("Certificate").Bind(certSettings);
|
||||
if (string.IsNullOrWhiteSpace(certSettings.Path))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Certificate.Path must be provided via configuration and should point to the mounted Kubernetes secret file.");
|
||||
}
|
||||
services.AddSingleton(certSettings);
|
||||
|
||||
var proxySettings = new ProxySettings();
|
||||
configuration.GetSection("Proxy").Bind(proxySettings);
|
||||
services.AddSingleton(proxySettings);
|
||||
|
||||
// Cert provider
|
||||
if (certSettings.UseFile)
|
||||
{
|
||||
services.AddSingleton<ICertificateProvider>(
|
||||
new FileCertificateProvider(
|
||||
certSettings.FilePath ?? throw new InvalidOperationException(
|
||||
"Certificate.FilePath must be set when Certificate.UseFile is true."),
|
||||
certSettings.Password ?? throw new InvalidOperationException(
|
||||
"Certificate.Password must be set when Certificate.UseFile is true."))
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(certSettings.FriendlyName) &&
|
||||
string.IsNullOrWhiteSpace(certSettings.Thumbprint))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"When Certificate.UseFile is false, set at least one of Certificate.FriendlyName or Certificate.Thumbprint.");
|
||||
}
|
||||
|
||||
services.AddSingleton<ICertificateProvider>(
|
||||
new WindowsCertificateProvider(
|
||||
certSettings.FriendlyName,
|
||||
certSettings.Thumbprint));
|
||||
}
|
||||
services.AddSingleton<ICertificateProvider>(
|
||||
new FileCertificateProvider(certSettings.Path, certSettings.Password));
|
||||
|
||||
//Http Client
|
||||
services.AddSingleton<HttpClient>(sp =>
|
||||
|
||||
@@ -34,7 +34,7 @@ namespace MaxInventory.Infrastructure.Http
|
||||
}
|
||||
|
||||
//Ensure the base URL ends with a trailing slash for proper relative URL resolution
|
||||
var baseUrl = apiSettings.BaseUrl.TrimEnd('/') + "/";
|
||||
var baseUrl = apiSettings.BaseUrl!.TrimEnd('/') + "/";
|
||||
|
||||
var client = new HttpClient(handler)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
namespace MaxInventory.Web.Components.Pages;
|
||||
namespace MaxInventory.Web.Components.Pages;
|
||||
|
||||
using MaxInventory.Authentication.Abstractions;
|
||||
using MaxInventory.Core.Configuration;
|
||||
using MaxInventory.Core.Enums;
|
||||
using MaxInventory.Core.Models;
|
||||
@@ -28,10 +29,11 @@ public partial class ContentTypePage : ComponentBase
|
||||
[Inject] public required IInventoryApiClient ApiClient { get; set; }
|
||||
[Inject] public required IRelationshipRegistry RelationshipRegistry { get; set; }
|
||||
[Inject] public required IToastService ToastService { get; set; }
|
||||
[Inject] public required IPrincipalAccessEvaluator PrincipalAccessEvaluator { get; set; }
|
||||
|
||||
[Inject] public required AuthenticationStateProvider AuthenticationStateProvider { get; set; }
|
||||
|
||||
// ── Page State ───────────────────────────────────────────────────
|
||||
// -- Page State ---------------------------------------------------
|
||||
private ContentTypeDefinition? _definition;
|
||||
private ContentTypeDefinition? _formDefinition;
|
||||
private List<IInventoryEntity> _items = new();
|
||||
@@ -54,7 +56,7 @@ public partial class ContentTypePage : ComponentBase
|
||||
/// </summary>
|
||||
private readonly Dictionary<ContentTypeName, IReadOnlyList<IInventoryEntity>> _dataCache = new();
|
||||
|
||||
// ── Lifecycle ────────────────────────────────────────────────────
|
||||
// -- Lifecycle ----------------------------------------------------
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
{
|
||||
@@ -89,13 +91,13 @@ public partial class ContentTypePage : ComponentBase
|
||||
}
|
||||
if (EditId.HasValue)
|
||||
{
|
||||
var editItem = _items.FirstOrDefault(i => i.Id == HighlightId.Value);
|
||||
var editItem = _items.FirstOrDefault(i => i.Id == EditId.Value);
|
||||
if (editItem != null && _canEdit)
|
||||
ShowEditForm(editItem);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Data Loading ─────────────────────────────────────────────────
|
||||
// -- Data Loading -------------------------------------------------
|
||||
|
||||
private async Task LoadDataAsync()
|
||||
{
|
||||
@@ -157,7 +159,7 @@ public partial class ContentTypePage : ComponentBase
|
||||
}
|
||||
|
||||
|
||||
// ── Row Selection ─────────────────────────────────────────────────
|
||||
// -- Row Selection -------------------------------------------------
|
||||
|
||||
private void SelectItem(IInventoryEntity item)
|
||||
{
|
||||
@@ -202,7 +204,7 @@ public partial class ContentTypePage : ComponentBase
|
||||
}
|
||||
}
|
||||
|
||||
// ── CRUD ─────────────────────────────────────────────────────────
|
||||
// -- CRUD ---------------------------------------------------------
|
||||
|
||||
private void ShowAddForm()
|
||||
{
|
||||
@@ -338,7 +340,7 @@ public partial class ContentTypePage : ComponentBase
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────
|
||||
// -- Helpers ------------------------------------------------------
|
||||
|
||||
private string GetDisplayName(IInventoryEntity entity)
|
||||
{
|
||||
@@ -378,13 +380,11 @@ public partial class ContentTypePage : ComponentBase
|
||||
private async Task ResolvePermissionsAsync()
|
||||
{
|
||||
var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
|
||||
var user = state.User;
|
||||
|
||||
_canView = user.Identity?.IsAuthenticated == true &&
|
||||
(user.IsInRole("View") || user.IsInRole("EditAdd") || user.IsInRole("Admin"));
|
||||
_canEdit = user.Identity?.IsAuthenticated == true &&
|
||||
(user.IsInRole("EditAdd") || user.IsInRole("Admin"));
|
||||
_canDelete = user.Identity?.IsAuthenticated == true && user.IsInRole("Admin");
|
||||
var access = await PrincipalAccessEvaluator.EvaluateAsync(state.User);
|
||||
_canView = access.CanView;
|
||||
_canEdit = access.CanEdit;
|
||||
_canDelete = access.CanDelete;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\MaxInventory.Authentication\MaxInventory.Authentication.csproj" />
|
||||
<ProjectReference Include="..\MaxInventory.Authentication\MaxInventory.Authentication.csproj" />
|
||||
<ProjectReference Include="..\MaxInventory.Core\MaxInventory.Core.csproj" />
|
||||
<ProjectReference Include="..\MaxInventory.Infrastructure\MaxInventory.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -7,14 +7,10 @@
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Api": {
|
||||
"BaseUrl": "https://directauth.max.gov/inventory",
|
||||
"TimeoutSeconds": 30
|
||||
},
|
||||
"Certificate": {
|
||||
"UseFile": false,
|
||||
"FriendlyName": "alleman_j inventory.max.gov client",
|
||||
"Thumbprint": "92e8b18ac60363bf2f761b7a0cd6d1228d707454",
|
||||
"FilePath": null,
|
||||
"Path": null,
|
||||
"Password": null
|
||||
},
|
||||
"Proxy": {
|
||||
|
||||
Reference in New Issue
Block a user