This commit is contained in:
Ccjcarkbla
2026-05-27 08:43:11 -04:00
parent c1f3dff01d
commit a0a3615188
11 changed files with 240 additions and 201 deletions
@@ -0,0 +1,16 @@
using System.Security.Claims;
namespace MaxInventory.Core.Services
{
/// <summary>
/// Applies per-user authentication material to outbound inventory API requests.
/// </summary>
public interface IInventoryApiAuthenticator
{
Task AuthenticateAsync(
HttpRequestMessage request,
ClaimsPrincipal principal,
Uri targetService,
CancellationToken cancellationToken = default);
}
}
@@ -1,4 +1,5 @@
using MaxInventory.Core.Models; using System.Security.Claims;
using MaxInventory.Core.Models;
namespace MaxInventory.Core.Services namespace MaxInventory.Core.Services
{ {
@@ -11,37 +12,33 @@ namespace MaxInventory.Core.Services
/// <summary> /// <summary>
/// Retrieves all records of the specified type from the given endpoint. /// Retrieves all records of the specified type from the given endpoint.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> Task<List<T>> GetAllAsync<T>(ClaimsPrincipal principal, string endpoint, CancellationToken ct = default)
/// <param name="endpoint"></param> where T : class, IInventoryEntity;
/// <param name="ct"></param>
/// <returns></returns>
Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default) where T : class, IInventoryEntity;
/// <summary> /// <summary>
/// Creates new record at the given endpoint. Returns the server-assigned ID. /// Creates new record at the given endpoint. Returns the server-assigned ID.
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> Task<ApiCreateResponse> CreateAsync<T>(
/// <param name="endpoint"></param> ClaimsPrincipal principal,
/// <param name="entity"></param> string endpoint,
/// <param name="ct"></param> T entity,
/// <returns></returns> CancellationToken ct = default)
Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default) where T : class, IInventoryEntity; where T : class, IInventoryEntity;
/// <summary> /// <summary>
/// Updates an existing record by ID at the given endpoint (HTTP PUT). /// Updates an existing record by ID at the given endpoint (HTTP PUT).
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> Task UpdateAsync<T>(
/// <param name="endpoint"></param> ClaimsPrincipal principal,
/// <param name="id"></param> string endpoint,
/// <param name="entity"></param> int id,
/// <param name="ct"></param> T entity,
/// <returns></returns> CancellationToken ct = default)
Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default) where T : class, IInventoryEntity; where T : class, IInventoryEntity;
/// <summary> /// <summary>
/// Deletes a record by ID at the given endpoint. /// Deletes a record by ID at the given endpoint.
/// </summary> /// </summary>
/// <param name="endpoint"></param> Task DeleteAsync(ClaimsPrincipal principal, string endpoint, int id, CancellationToken ct = default);
/// <param name="id"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task DeleteAsync(string endpoint, int id, CancellationToken ct = default);
} }
} }
@@ -15,5 +15,16 @@
/// HTTP request timeout in seconds. Default is 30. /// HTTP request timeout in seconds. Default is 30.
/// </summary> /// </summary>
public int TimeoutSeconds { get; set; } = 30; public int TimeoutSeconds { get; set; } = 30;
/// <summary>
/// Optional CAS target service override used when requesting proxy tickets for the API.
/// When omitted, the outbound API request URI is used as the target service.
/// </summary>
public string? CasTargetService { get; set; }
/// <summary>
/// Header used to pass the CAS proxy ticket to the inventory API.
/// </summary>
public string CasProxyTicketHeaderName { get; set; } = "X-CAS-Proxy-Ticket";
} }
} }
@@ -1,11 +1,10 @@
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using MaxInventory.Core.Registry; using MaxInventory.Core.Registry;
using MaxInventory.Core.Services; using MaxInventory.Core.Services;
using MaxInventory.Core.Settings; using MaxInventory.Core.Settings;
using MaxInventory.Infrastructure.Certificates; using MaxInventory.Infrastructure.Certificates;
using MaxInventory.Infrastructure.Http; using MaxInventory.Infrastructure.Http;
using System.Runtime.CompilerServices;
namespace MaxInventory.Infrastructure.Extensions namespace MaxInventory.Infrastructure.Extensions
{ {
@@ -16,8 +15,8 @@ namespace MaxInventory.Infrastructure.Extensions
public static class ServiceCollectionExtensions public static class ServiceCollectionExtensions
{ {
///<summary> ///<summary>
/// Registers all inventory services: settings, certificate provider, HTTP client, /// Registers all inventory services: settings, HTTP client, API client,
/// API client, registeries, and serializer. /// registries, and serializer.
/// </summary> /// </summary>
public static IServiceCollection AddInventoryServices( public static IServiceCollection AddInventoryServices(
this IServiceCollection services, this IServiceCollection services,
@@ -63,14 +62,11 @@ namespace MaxInventory.Infrastructure.Extensions
} }
//Http Client //Http Client
services.AddSingleton<HttpClient>(sp => services.AddSingleton(sp => InventoryHttpClientFactory.Create(apiSettings, proxySettings));
{
var certProvider = sp.GetRequiredService<ICertificateProvider>();
return InventoryHttpClientFactory.Create(certProvider, apiSettings, proxySettings);
});
// API Client // API Client
services.AddSingleton<IInventoryApiClient, InventoryApiClient>(); services.AddScoped<IInventoryApiAuthenticator, NoOpInventoryApiAuthenticator>();
services.AddScoped<IInventoryApiClient, InventoryApiClient>();
// Serializer // Serializer
services.AddSingleton<IEntitySerializer, EntitySerializer>(); services.AddSingleton<IEntitySerializer, EntitySerializer>();
@@ -1,293 +1,242 @@
namespace MaxInventory.Infrastructure.Http; namespace MaxInventory.Infrastructure.Http;
using System.Net;
using System.Security.Claims;
using System.Text; using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using MaxInventory.Core.Models; using MaxInventory.Core.Models;
using MaxInventory.Core.Services; using MaxInventory.Core.Services;
/// <summary> /// <summary>
/// Implementation of IInventoryApiClient that communicates with the inventory REST API.
/// Implementation of IInventoryApiClient that communicates with the
/// inventory REST API using HttpClient with certificate authentication.
/// All CRUD operations go through this single class. /// All CRUD operations go through this single class.
/// </summary> /// </summary>
public sealed class InventoryApiClient : IInventoryApiClient public sealed class InventoryApiClient : IInventoryApiClient
{ {
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly IInventoryApiAuthenticator _authenticator;
private readonly JsonSerializerOptions _jsonOptions; private readonly JsonSerializerOptions _jsonOptions;
public InventoryApiClient(HttpClient httpClient) public InventoryApiClient(HttpClient httpClient, IInventoryApiAuthenticator authenticator)
{ {
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator));
_jsonOptions = new JsonSerializerOptions _jsonOptions = new JsonSerializerOptions
{ {
PropertyNamingPolicy = null, // We use explicit [JsonPropertyName] attributes PropertyNamingPolicy = null, // We use explicit [JsonPropertyName] attributes
PropertyNameCaseInsensitive = true,
            PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString, NumberHandling = JsonNumberHandling.AllowReadingFromString,
WriteIndented = false, WriteIndented = false,
}; };
_jsonOptions.Converters.Add(new FlexibleStringJsonConverter()); _jsonOptions.Converters.Add(new FlexibleStringJsonConverter());
} }
    /// <inheritdoc /> /// <inheritdoc />
public async Task<List<T>> GetAllAsync<T>(
    public async Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default) ClaimsPrincipal principal,
string endpoint,
where T : class, IInventoryEntity CancellationToken ct = default)
where T : class, IInventoryEntity
{ {
var endpointsToTry = GetFallbackEndpoints(endpoint); var endpointsToTry = GetFallbackEndpoints(endpoint);
HttpRequestException? lastNotFound = null; HttpRequestException? lastNotFound = null;
for (var i = 0; i < endpointsToTry.Count; i++) for (var i = 0; i < endpointsToTry.Count; i++)
{ {
var candidate = endpointsToTry[i]; var candidate = endpointsToTry[i];
var url = ApiEndpointResolver.Resolve(candidate); var url = ApiEndpointResolver.Resolve(candidate);
using var request = await CreateRequestAsync(HttpMethod.Get, principal, url, ct);
var response = await _httpClient.GetAsync(url, ct); using var response = await _httpClient.SendAsync(request, ct);
if (response.IsSuccessStatusCode) if (response.IsSuccessStatusCode)
{ {
var json = await response.Content.ReadAsStringAsync(ct); var json = await response.Content.ReadAsStringAsync(ct);
var parsed = JsonSerializer.Deserialize<List<T>>(json, _jsonOptions) ?? new List<T>(); var parsed = JsonSerializer.Deserialize<List<T>>(json, _jsonOptions) ?? new List<T>();
                // Some inventory APIs return 200 with empty arrays for one alias // Some inventory APIs return 200 with empty arrays for one alias
// while another alias (usually singular/plural) contains the data.
                // while another alias (usually singular/plural) contains the data. // If this candidate is empty and we still have fallbacks, try them.
if (parsed.Count == 0 && i < endpointsToTry.Count - 1)
                // If this candidate is empty and we still have fallbacks, try them. {
                if (parsed.Count == 0 && i < endpointsToTry.Count - 1)
continue; continue;
}
return parsed; return parsed;
} }
if (response.StatusCode == System.Net.HttpStatusCode.NotFound) if (response.StatusCode == HttpStatusCode.NotFound)
{ {
var body = await response.Content.ReadAsStringAsync(ct); var body = await response.Content.ReadAsStringAsync(ct);
lastNotFound = new HttpRequestException( lastNotFound = new HttpRequestException(
$"Request to '{response.RequestMessage?.RequestUri}' failed with " +
$"Request to '{response.RequestMessage?.RequestUri}' failed with " + $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {TrimBody(body)}");
$"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {TrimBody(body)}");
continue; continue;
} }
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
} }
throw lastNotFound ?? new HttpRequestException( throw lastNotFound ?? new HttpRequestException(
$"Request to endpoint '{endpoint}' failed after trying fallbacks: {string.Join(", ", endpointsToTry)}");
$"Request to endpoint '{endpoint}' failed after trying fallbacks: {string.Join(", ", endpointsToTry)}");
} }
    /// <inheritdoc /> /// <inheritdoc />
public async Task<ApiCreateResponse> CreateAsync<T>(
    public async Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default) ClaimsPrincipal principal,
string endpoint,
where T : class, IInventoryEntity T entity,
CancellationToken ct = default)
where T : class, IInventoryEntity
{ {
var url = ApiEndpointResolver.Resolve(endpoint); var url = ApiEndpointResolver.Resolve(endpoint);
var json = JsonSerializer.Serialize(entity, _jsonOptions); var json = JsonSerializer.Serialize(entity, _jsonOptions);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var request = await CreateRequestAsync(HttpMethod.Post, principal, url, ct);
request.Content = content;
var content = new StringContent(json, Encoding.UTF8, "application/json"); using var response = await _httpClient.SendAsync(request, ct);
var response = await _httpClient.PostAsync(url, content, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
var responseJson = await response.Content.ReadAsStringAsync(ct); var responseJson = await response.Content.ReadAsStringAsync(ct);
return JsonSerializer.Deserialize<ApiCreateResponse>(responseJson, _jsonOptions) return JsonSerializer.Deserialize<ApiCreateResponse>(responseJson, _jsonOptions)
?? throw new InvalidOperationException("API returned null response on create.");
?? throw new InvalidOperationException("API returned null response on create.");
} }
    /// <inheritdoc /> /// <inheritdoc />
public async Task UpdateAsync<T>(
    public async Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default) ClaimsPrincipal principal,
string endpoint,
where T : class, IInventoryEntity int id,
T entity,
CancellationToken ct = default)
where T : class, IInventoryEntity
{ {
var url = ApiEndpointResolver.ResolveWithId(endpoint, id); var url = ApiEndpointResolver.ResolveWithId(endpoint, id);
var json = JsonSerializer.Serialize(entity, _jsonOptions); var json = JsonSerializer.Serialize(entity, _jsonOptions);
using var content = new StringContent(json, Encoding.UTF8, "application/json");
using var request = await CreateRequestAsync(HttpMethod.Put, principal, url, ct);
request.Content = content;
var content = new StringContent(json, Encoding.UTF8, "application/json"); using var response = await _httpClient.SendAsync(request, ct);
var response = await _httpClient.PutAsync(url, content, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
} }
    /// <inheritdoc /> /// <inheritdoc />
public async Task DeleteAsync(
    public async Task DeleteAsync(string endpoint, int id, CancellationToken ct = default) ClaimsPrincipal principal,
string endpoint,
int id,
CancellationToken ct = default)
{ {
var url = ApiEndpointResolver.ResolveWithId(endpoint, id); var url = ApiEndpointResolver.ResolveWithId(endpoint, id);
using var request = await CreateRequestAsync(HttpMethod.Delete, principal, url, ct);
var response = await _httpClient.DeleteAsync(url, ct); using var response = await _httpClient.SendAsync(request, ct);
await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct);
}
private async Task<HttpRequestMessage> CreateRequestAsync(
HttpMethod method,
ClaimsPrincipal principal,
string url,
CancellationToken ct)
{
var request = new HttpRequestMessage(method, url);
await _authenticator.AuthenticateAsync(request, principal, ResolveTargetService(url), ct);
return request;
}
private Uri ResolveTargetService(string url)
{
if (Uri.TryCreate(url, UriKind.Absolute, out var absoluteUri))
{
return absoluteUri;
}
if (_httpClient.BaseAddress is null)
{
throw new InvalidOperationException("Inventory API HttpClient must have a BaseAddress.");
}
return new Uri(_httpClient.BaseAddress, url);
} }
private static async Task EnsureSuccessStatusCodeWithDetailsAsync( private static async Task EnsureSuccessStatusCodeWithDetailsAsync(
HttpResponseMessage response,
HttpResponseMessage response, CancellationToken ct)
CancellationToken ct)
{ {
if (response.IsSuccessStatusCode)
if (response.IsSuccessStatusCode) return; {
return;
}
var body = TrimBody(await response.Content.ReadAsStringAsync(ct)); var body = TrimBody(await response.Content.ReadAsStringAsync(ct));
throw new HttpRequestException( throw new HttpRequestException(
$"Request to '{response.RequestMessage?.RequestUri}' failed with " +
$"Request to '{response.RequestMessage?.RequestUri}' failed with " + $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {body}");
$"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {body}");
} }
private static IReadOnlyList<string> GetFallbackEndpoints(string endpoint) private static IReadOnlyList<string> GetFallbackEndpoints(string endpoint)
{ {
if (string.Equals(endpoint, "systems", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "systems", StringComparison.OrdinalIgnoreCase))
return new[] { "systems", "system" }; return new[] { "systems", "system" };
if (string.Equals(endpoint, "devices", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "devices", StringComparison.OrdinalIgnoreCase))
return new[] { "devices", "device" }; return new[] { "devices", "device" };
if (string.Equals(endpoint, "ips", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "ips", StringComparison.OrdinalIgnoreCase))
return new[] { "ips", "ip" }; return new[] { "ips", "ip" };
if (string.Equals(endpoint, "subnets", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "subnets", StringComparison.OrdinalIgnoreCase))
return new[] { "subnets", "subnet" }; return new[] { "subnets", "subnet" };
if (string.Equals(endpoint, "customer_zones", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "customer_zones", StringComparison.OrdinalIgnoreCase))
return new[] { "customer_zones", "customer_zone" }; return new[] { "customer_zones", "customer_zone" };
if (string.Equals(endpoint, "application_zones", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "application_zones", StringComparison.OrdinalIgnoreCase))
return new[] { "application_zones", "application_zone" }; return new[] { "application_zones", "application_zone" };
if (string.Equals(endpoint, "vms", StringComparison.OrdinalIgnoreCase)) if (string.Equals(endpoint, "vms", StringComparison.OrdinalIgnoreCase))
return new[] { "vms", "vm", "virtual_machines", "systems", "system" }; return new[] { "vms", "vm", "virtual_machines", "systems", "system" };
return new[] { endpoint }; return new[] { endpoint };
} }
private static string TrimBody(string body) private static string TrimBody(string body)
{ {
if (body.Length > 400) if (body.Length > 400)
{
return body[..400] + "..."; return body[..400] + "...";
}
return body; return body;
} }
private sealed class FlexibleStringJsonConverter : JsonConverter<string> private sealed class FlexibleStringJsonConverter : JsonConverter<string>
{ {
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{ {
if (reader.TokenType == JsonTokenType.String) if (reader.TokenType == JsonTokenType.String)
return reader.GetString() ?? string.Empty; return reader.GetString() ?? string.Empty;
if (reader.TokenType == JsonTokenType.Number) if (reader.TokenType == JsonTokenType.Number)
return reader.GetDouble().ToString(System.Globalization.CultureInfo.InvariantCulture); return reader.GetDouble().ToString(System.Globalization.CultureInfo.InvariantCulture);
if (reader.TokenType == JsonTokenType.True) if (reader.TokenType == JsonTokenType.True)
return bool.TrueString; return bool.TrueString;
if (reader.TokenType == JsonTokenType.False) if (reader.TokenType == JsonTokenType.False)
return bool.FalseString; return bool.FalseString;
if (reader.TokenType == JsonTokenType.Null) if (reader.TokenType == JsonTokenType.Null)
return string.Empty; return string.Empty;
using var doc = JsonDocument.ParseValue(ref reader); using var doc = JsonDocument.ParseValue(ref reader);
return doc.RootElement.ToString(); return doc.RootElement.ToString();
} }
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
=> writer.WriteStringValue(value);
=> writer.WriteStringValue(value);
} }
} }
@@ -1,27 +1,19 @@
using System.Net; using System.Net;
using MaxInventory.Core.Services;
using MaxInventory.Core.Settings; using MaxInventory.Core.Settings;
namespace MaxInventory.Infrastructure.Http namespace MaxInventory.Infrastructure.Http
{ {
/// <summary> /// <summary>
/// Factory for creating an HttpClient configured with certificate authentication, /// Factory for creating an HttpClient configured with proxy settings
/// proxy settings, and the correct base URL for the inventory API. /// and the correct base URL for the inventory API.
/// </summary> /// </summary>
public static class InventoryHttpClientFactory public static class InventoryHttpClientFactory
{ {
///<summary> Creates a fully configured HttpClient for the inventory API.</summary> ///<summary> Creates a fully configured HttpClient for the inventory API.</summary>
public static HttpClient Create( public static HttpClient Create(ApiSettings apiSettings, ProxySettings proxySettings)
ICertificateProvider certificateProvider,
ApiSettings apiSettings,
ProxySettings proxySettings)
{ {
var handler = new HttpClientHandler(); var handler = new HttpClientHandler();
//Attach client certificate for mutual TLS
var cert = certificateProvider.GetClientCertificate();
handler.ClientCertificates.Add(cert);
//Configure proxy if enabled //Configure proxy if enabled
if (proxySettings.Enabled && !string.IsNullOrEmpty(proxySettings.Address)) if (proxySettings.Enabled && !string.IsNullOrEmpty(proxySettings.Address))
{ {
@@ -0,0 +1,16 @@
using System.Security.Claims;
using MaxInventory.Core.Services;
namespace MaxInventory.Infrastructure.Http;
internal sealed class NoOpInventoryApiAuthenticator : IInventoryApiAuthenticator
{
public Task AuthenticateAsync(
HttpRequestMessage request,
ClaimsPrincipal principal,
Uri targetService,
CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
}
@@ -1,5 +1,6 @@
namespace MaxInventory.Web.Components.Pages; namespace MaxInventory.Web.Components.Pages;
using System.Security.Claims;
using MaxInventory.Authentication.Abstractions; using MaxInventory.Authentication.Abstractions;
using MaxInventory.Core.Configuration; using MaxInventory.Core.Configuration;
using MaxInventory.Core.Enums; using MaxInventory.Core.Enums;
@@ -92,7 +93,7 @@ public partial class ContentTypePage : ComponentBase
} }
if (EditId.HasValue) 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) if (editItem != null && _canEdit)
ShowEditForm(editItem); ShowEditForm(editItem);
} }
@@ -222,8 +223,9 @@ public partial class ContentTypePage : ComponentBase
.GetMethod(nameof(IInventoryApiClient.GetAllAsync))! .GetMethod(nameof(IInventoryApiClient.GetAllAsync))!
.MakeGenericMethod(def.ModelType); .MakeGenericMethod(def.ModelType);
var principal = await GetCurrentUserAsync();
var task = (System.Threading.Tasks.Task)method.Invoke( var task = (System.Threading.Tasks.Task)method.Invoke(
ApiClient, new object[] { def.ApiEndpoint, CancellationToken.None })!; ApiClient, new object[] { principal, def.ApiEndpoint, CancellationToken.None })!;
await task; await task;
var result = task.GetType().GetProperty("Result")!.GetValue(task); var result = task.GetType().GetProperty("Result")!.GetValue(task);
@@ -336,8 +338,9 @@ public partial class ContentTypePage : ComponentBase
.GetMethod(nameof(IInventoryApiClient.CreateAsync))! .GetMethod(nameof(IInventoryApiClient.CreateAsync))!
.MakeGenericMethod(activeDefinition.ModelType); .MakeGenericMethod(activeDefinition.ModelType);
var principal = await GetCurrentUserAsync();
var task = (System.Threading.Tasks.Task)createMethod.Invoke( var task = (System.Threading.Tasks.Task)createMethod.Invoke(
ApiClient, new object[] { activeDefinition.ApiEndpoint, entity, CancellationToken.None })!; ApiClient, new object[] { principal, activeDefinition.ApiEndpoint, entity, CancellationToken.None })!;
await task; await task;
ToastService.ShowSuccess($"{activeDefinition.DisplayName} created successfully."); ToastService.ShowSuccess($"{activeDefinition.DisplayName} created successfully.");
@@ -349,8 +352,9 @@ public partial class ContentTypePage : ComponentBase
.GetMethod(nameof(IInventoryApiClient.UpdateAsync))! .GetMethod(nameof(IInventoryApiClient.UpdateAsync))!
.MakeGenericMethod(activeDefinition.ModelType); .MakeGenericMethod(activeDefinition.ModelType);
var principal = await GetCurrentUserAsync();
var task = (System.Threading.Tasks.Task)updateMethod.Invoke( var task = (System.Threading.Tasks.Task)updateMethod.Invoke(
ApiClient, new object[] { activeDefinition.ApiEndpoint, entity.Id, entity, CancellationToken.None })!; ApiClient, new object[] { principal, activeDefinition.ApiEndpoint, entity.Id, entity, CancellationToken.None })!;
await task; await task;
ToastService.ShowSuccess($"{activeDefinition.DisplayName} updated successfully."); ToastService.ShowSuccess($"{activeDefinition.DisplayName} updated successfully.");
@@ -385,7 +389,8 @@ public partial class ContentTypePage : ComponentBase
try try
{ {
await ApiClient.DeleteAsync(_definition.ApiEndpoint, idToDelete); var principal = await GetCurrentUserAsync();
await ApiClient.DeleteAsync(principal, _definition.ApiEndpoint, idToDelete);
ToastService.ShowSuccess($"{_definition.DisplayName} deleted."); ToastService.ShowSuccess($"{_definition.DisplayName} deleted.");
if (_selectedItem?.Id == idToDelete) _selectedItem = null; if (_selectedItem?.Id == idToDelete) _selectedItem = null;
@@ -437,13 +442,18 @@ public partial class ContentTypePage : ComponentBase
private async Task ResolvePermissionsAsync() private async Task ResolvePermissionsAsync()
{ {
var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var principal = await GetCurrentUserAsync();
var access = await PrincipalAccessEvaluator.EvaluateAsync(state.User); var access = await PrincipalAccessEvaluator.EvaluateAsync(principal);
_canView = access.CanView; _canView = access.CanView;
_canEdit = access.CanEdit; _canEdit = access.CanEdit;
_canDelete = access.CanDelete; _canDelete = access.CanDelete;
} }
private async Task<ClaimsPrincipal> GetCurrentUserAsync()
{
var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
return state.User;
}
} }
+10
View File
@@ -1,5 +1,7 @@
using MaxInventory.Authentication.Core; using MaxInventory.Authentication.Core;
using MaxInventory.Authentication.Configuration;
using MaxInventory.Authentication.Extensions; using MaxInventory.Authentication.Extensions;
using MaxInventory.Core.Services;
using MaxInventory.Infrastructure.Extensions; using MaxInventory.Infrastructure.Extensions;
using MaxInventory.Web.Components; using MaxInventory.Web.Components;
using MaxInventory.Web.Services; using MaxInventory.Web.Services;
@@ -33,6 +35,14 @@ builder.Services.AddCascadingAuthenticationState();
builder.Services.AddInventoryServices(builder.Configuration); builder.Services.AddInventoryServices(builder.Configuration);
builder.Services.AddAuthentication(builder.Configuration); builder.Services.AddAuthentication(builder.Configuration);
if (string.Equals(
builder.Configuration[AuthEnvironment.AuthMode],
AuthModes.Cas,
StringComparison.OrdinalIgnoreCase))
{
builder.Services.AddScoped<IInventoryApiAuthenticator, CasInventoryApiAuthenticator>();
}
builder.Services builder.Services
.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme) .AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
.Configure<ITicketStore>((options, ticketStore) => .Configure<ITicketStore>((options, ticketStore) =>
@@ -0,0 +1,42 @@
using System.Security.Claims;
using MaxInventory.Authentication.Providers.Cas;
using MaxInventory.Core.Services;
using MaxInventory.Core.Settings;
namespace MaxInventory.Web.Services;
public sealed class CasInventoryApiAuthenticator : IInventoryApiAuthenticator
{
private readonly ICasProxyTicketService _proxyTicketService;
private readonly ApiSettings _apiSettings;
public CasInventoryApiAuthenticator(
ICasProxyTicketService proxyTicketService,
ApiSettings apiSettings)
{
_proxyTicketService = proxyTicketService;
_apiSettings = apiSettings;
}
public async Task AuthenticateAsync(
HttpRequestMessage request,
ClaimsPrincipal principal,
Uri targetService,
CancellationToken cancellationToken = default)
{
var service = string.IsNullOrWhiteSpace(_apiSettings.CasTargetService)
? targetService.ToString()
: _apiSettings.CasTargetService;
var proxyTicket = await _proxyTicketService
.GetProxyTicketAsync(principal, service, cancellationToken);
if (string.IsNullOrWhiteSpace(proxyTicket))
{
throw new InvalidOperationException("Unable to obtain a CAS proxy ticket for the inventory API request.");
}
request.Headers.Remove(_apiSettings.CasProxyTicketHeaderName);
request.Headers.Add(_apiSettings.CasProxyTicketHeaderName, proxyTicket);
}
}
+2 -2
View File
@@ -8,9 +8,9 @@
"AllowedHosts": "*", "AllowedHosts": "*",
"Api": { "Api": {
"BaseUrl": "https://directauth.max.gov/inventory", "BaseUrl": "https://directauth.max.gov/inventory",
"TimeoutSeconds": 30 "TimeoutSeconds": 30,
"CasProxyTicketHeaderName": "X-CAS-Proxy-Ticket"
}, },
"Proxy": { "Proxy": {
"Enabled": true, "Enabled": true,
"Address": "http://proxy.omb.gov:8080" "Address": "http://proxy.omb.gov:8080"