From a0a361518830f40b8a86c9e88afa365df82d41fd Mon Sep 17 00:00:00 2001 From: Ccjcarkbla Date: Mon, 4 May 2026 12:48:12 -0400 Subject: [PATCH] CAS --- .../Services/IInventoryApiAuthenticator.cs | 16 ++ .../Services/IInventoryApiClient.cs | 45 ++-- src/MaxInventory.Core/Settings/ApiSettings.cs | 11 + .../Extensions/ServiceCollectionExtensions.cs | 16 +- .../Http/InventoryApiClient.cs | 239 +++++++----------- .../Http/InventoryHttpClientFactory.cs | 16 +- .../Http/NoOpInventoryApiAuthenticator.cs | 16 ++ .../Components/Pages/ContentTypePage.razor.cs | 26 +- src/MaxInventory.Web/Program.cs | 10 + .../Services/CasInventoryApiAuthenticator.cs | 42 +++ src/MaxInventory.Web/appsettings.json | 4 +- 11 files changed, 240 insertions(+), 201 deletions(-) create mode 100644 src/MaxInventory.Core/Services/IInventoryApiAuthenticator.cs create mode 100644 src/MaxInventory.Infrastructure/Http/NoOpInventoryApiAuthenticator.cs create mode 100644 src/MaxInventory.Web/Services/CasInventoryApiAuthenticator.cs diff --git a/src/MaxInventory.Core/Services/IInventoryApiAuthenticator.cs b/src/MaxInventory.Core/Services/IInventoryApiAuthenticator.cs new file mode 100644 index 0000000..587f1b6 --- /dev/null +++ b/src/MaxInventory.Core/Services/IInventoryApiAuthenticator.cs @@ -0,0 +1,16 @@ +using System.Security.Claims; + +namespace MaxInventory.Core.Services +{ + /// + /// Applies per-user authentication material to outbound inventory API requests. + /// + public interface IInventoryApiAuthenticator + { + Task AuthenticateAsync( + HttpRequestMessage request, + ClaimsPrincipal principal, + Uri targetService, + CancellationToken cancellationToken = default); + } +} diff --git a/src/MaxInventory.Core/Services/IInventoryApiClient.cs b/src/MaxInventory.Core/Services/IInventoryApiClient.cs index 60bcd26..30a93c8 100644 --- a/src/MaxInventory.Core/Services/IInventoryApiClient.cs +++ b/src/MaxInventory.Core/Services/IInventoryApiClient.cs @@ -1,4 +1,5 @@ -using MaxInventory.Core.Models; +using System.Security.Claims; +using MaxInventory.Core.Models; namespace MaxInventory.Core.Services { @@ -11,37 +12,33 @@ namespace MaxInventory.Core.Services /// /// Retrieves all records of the specified type from the given endpoint. /// - /// - /// - /// - /// - Task> GetAllAsync(string endpoint, CancellationToken ct = default) where T : class, IInventoryEntity; + Task> GetAllAsync(ClaimsPrincipal principal, string endpoint, CancellationToken ct = default) + where T : class, IInventoryEntity; + /// /// Creates new record at the given endpoint. Returns the server-assigned ID. /// - /// - /// - /// - /// - /// - Task CreateAsync(string endpoint, T entity, CancellationToken ct = default) where T : class, IInventoryEntity; + Task CreateAsync( + ClaimsPrincipal principal, + string endpoint, + T entity, + CancellationToken ct = default) + where T : class, IInventoryEntity; + /// /// Updates an existing record by ID at the given endpoint (HTTP PUT). /// - /// - /// - /// - /// - /// - /// - Task UpdateAsync(string endpoint, int id, T entity, CancellationToken ct = default) where T : class, IInventoryEntity; + Task UpdateAsync( + ClaimsPrincipal principal, + string endpoint, + int id, + T entity, + CancellationToken ct = default) + where T : class, IInventoryEntity; + /// /// Deletes a record by ID at the given endpoint. /// - /// - /// - /// - /// - Task DeleteAsync(string endpoint, int id, CancellationToken ct = default); + Task DeleteAsync(ClaimsPrincipal principal, string endpoint, int id, CancellationToken ct = default); } } diff --git a/src/MaxInventory.Core/Settings/ApiSettings.cs b/src/MaxInventory.Core/Settings/ApiSettings.cs index b27f6ab..b861c23 100644 --- a/src/MaxInventory.Core/Settings/ApiSettings.cs +++ b/src/MaxInventory.Core/Settings/ApiSettings.cs @@ -15,5 +15,16 @@ /// HTTP request timeout in seconds. Default is 30. /// public int TimeoutSeconds { get; set; } = 30; + + /// + /// 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. + /// + public string? CasTargetService { get; set; } + + /// + /// Header used to pass the CAS proxy ticket to the inventory API. + /// + public string CasProxyTicketHeaderName { get; set; } = "X-CAS-Proxy-Ticket"; } } diff --git a/src/MaxInventory.Infrastructure/Extensions/ServiceCollectionExtensions.cs b/src/MaxInventory.Infrastructure/Extensions/ServiceCollectionExtensions.cs index 8327b74..1d4b342 100644 --- a/src/MaxInventory.Infrastructure/Extensions/ServiceCollectionExtensions.cs +++ b/src/MaxInventory.Infrastructure/Extensions/ServiceCollectionExtensions.cs @@ -1,11 +1,10 @@ -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MaxInventory.Core.Registry; using MaxInventory.Core.Services; using MaxInventory.Core.Settings; using MaxInventory.Infrastructure.Certificates; using MaxInventory.Infrastructure.Http; -using System.Runtime.CompilerServices; namespace MaxInventory.Infrastructure.Extensions { @@ -16,8 +15,8 @@ namespace MaxInventory.Infrastructure.Extensions public static class ServiceCollectionExtensions { /// - /// Registers all inventory services: settings, certificate provider, HTTP client, - /// API client, registeries, and serializer. + /// Registers all inventory services: settings, HTTP client, API client, + /// registries, and serializer. /// public static IServiceCollection AddInventoryServices( this IServiceCollection services, @@ -63,14 +62,11 @@ namespace MaxInventory.Infrastructure.Extensions } //Http Client - services.AddSingleton(sp => - { - var certProvider = sp.GetRequiredService(); - return InventoryHttpClientFactory.Create(certProvider, apiSettings, proxySettings); - }); + services.AddSingleton(sp => InventoryHttpClientFactory.Create(apiSettings, proxySettings)); // API Client - services.AddSingleton(); + services.AddScoped(); + services.AddScoped(); // Serializer services.AddSingleton(); diff --git a/src/MaxInventory.Infrastructure/Http/InventoryApiClient.cs b/src/MaxInventory.Infrastructure/Http/InventoryApiClient.cs index 4214a79..eec1eda 100644 --- a/src/MaxInventory.Infrastructure/Http/InventoryApiClient.cs +++ b/src/MaxInventory.Infrastructure/Http/InventoryApiClient.cs @@ -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.Json; - using System.Text.Json.Serialization; - using MaxInventory.Core.Models; - using MaxInventory.Core.Services; /// - -/// Implementation of IInventoryApiClient that communicates with the - -/// inventory REST API using HttpClient with certificate authentication. - +/// Implementation of IInventoryApiClient that communicates with the inventory REST API. /// All CRUD operations go through this single class. - /// - public sealed class InventoryApiClient : IInventoryApiClient - { - private readonly HttpClient _httpClient; - + private readonly IInventoryApiAuthenticator _authenticator; private readonly JsonSerializerOptions _jsonOptions; - public InventoryApiClient(HttpClient httpClient) - + public InventoryApiClient(HttpClient httpClient, IInventoryApiAuthenticator authenticator) { - _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); - + _authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); _jsonOptions = new JsonSerializerOptions - { - PropertyNamingPolicy = null, // We use explicit [JsonPropertyName] attributes - -            PropertyNameCaseInsensitive = true, - + PropertyNameCaseInsensitive = true, NumberHandling = JsonNumberHandling.AllowReadingFromString, - WriteIndented = false, - }; _jsonOptions.Converters.Add(new FlexibleStringJsonConverter()); - } -    /// - -    public async Task> GetAllAsync(string endpoint, CancellationToken ct = default) - - where T : class, IInventoryEntity - + /// + public async Task> GetAllAsync( + ClaimsPrincipal principal, + string endpoint, + CancellationToken ct = default) + where T : class, IInventoryEntity { - var endpointsToTry = GetFallbackEndpoints(endpoint); - HttpRequestException? lastNotFound = null; for (var i = 0; i < endpointsToTry.Count; i++) - { - var candidate = endpointsToTry[i]; - var url = ApiEndpointResolver.Resolve(candidate); - - var response = await _httpClient.GetAsync(url, ct); + using var request = await CreateRequestAsync(HttpMethod.Get, principal, url, ct); + using var response = await _httpClient.SendAsync(request, ct); if (response.IsSuccessStatusCode) - { - var json = await response.Content.ReadAsStringAsync(ct); - var parsed = JsonSerializer.Deserialize>(json, _jsonOptions) ?? new List(); -                // Some inventory APIs return 200 with empty arrays for one alias - -                // 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) - + // Some inventory APIs return 200 with empty arrays for one alias + // 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) + { continue; + } return parsed; - } - if (response.StatusCode == System.Net.HttpStatusCode.NotFound) - + if (response.StatusCode == HttpStatusCode.NotFound) { - var body = await response.Content.ReadAsStringAsync(ct); - lastNotFound = new HttpRequestException( - - $"Request to '{response.RequestMessage?.RequestUri}' failed with " + - - $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {TrimBody(body)}"); - + $"Request to '{response.RequestMessage?.RequestUri}' failed with " + + $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {TrimBody(body)}"); continue; - } await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); - } 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)}"); } -    /// - -    public async Task CreateAsync(string endpoint, T entity, CancellationToken ct = default) - - where T : class, IInventoryEntity - + /// + public async Task CreateAsync( + ClaimsPrincipal principal, + string endpoint, + T entity, + CancellationToken ct = default) + where T : class, IInventoryEntity { - var url = ApiEndpointResolver.Resolve(endpoint); - 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"); - - var response = await _httpClient.PostAsync(url, content, ct); - + using var response = await _httpClient.SendAsync(request, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); var responseJson = await response.Content.ReadAsStringAsync(ct); - return JsonSerializer.Deserialize(responseJson, _jsonOptions) - - ?? throw new InvalidOperationException("API returned null response on create."); - + ?? throw new InvalidOperationException("API returned null response on create."); } -    /// - -    public async Task UpdateAsync(string endpoint, int id, T entity, CancellationToken ct = default) - - where T : class, IInventoryEntity - + /// + public async Task UpdateAsync( + ClaimsPrincipal principal, + string endpoint, + int id, + T entity, + CancellationToken ct = default) + where T : class, IInventoryEntity { - var url = ApiEndpointResolver.ResolveWithId(endpoint, id); - 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"); - - var response = await _httpClient.PutAsync(url, content, ct); - + using var response = await _httpClient.SendAsync(request, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); - } -    /// - -    public async Task DeleteAsync(string endpoint, int id, CancellationToken ct = default) - + /// + public async Task DeleteAsync( + ClaimsPrincipal principal, + string endpoint, + int id, + CancellationToken ct = default) { - var url = ApiEndpointResolver.ResolveWithId(endpoint, id); - - var response = await _httpClient.DeleteAsync(url, ct); - + using var request = await CreateRequestAsync(HttpMethod.Delete, principal, url, ct); + using var response = await _httpClient.SendAsync(request, ct); await EnsureSuccessStatusCodeWithDetailsAsync(response, ct); + } + private async Task 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( - - HttpResponseMessage response, - - CancellationToken ct) - + HttpResponseMessage response, + CancellationToken ct) { - - if (response.IsSuccessStatusCode) return; + if (response.IsSuccessStatusCode) + { + return; + } var body = TrimBody(await response.Content.ReadAsStringAsync(ct)); - throw new HttpRequestException( - - $"Request to '{response.RequestMessage?.RequestUri}' failed with " + - - $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {body}"); - + $"Request to '{response.RequestMessage?.RequestUri}' failed with " + + $"{(int)response.StatusCode} ({response.ReasonPhrase}). Body: {body}"); } private static IReadOnlyList GetFallbackEndpoints(string endpoint) - { - if (string.Equals(endpoint, "systems", StringComparison.OrdinalIgnoreCase)) - return new[] { "systems", "system" }; if (string.Equals(endpoint, "devices", StringComparison.OrdinalIgnoreCase)) - return new[] { "devices", "device" }; if (string.Equals(endpoint, "ips", StringComparison.OrdinalIgnoreCase)) - return new[] { "ips", "ip" }; if (string.Equals(endpoint, "subnets", StringComparison.OrdinalIgnoreCase)) - return new[] { "subnets", "subnet" }; if (string.Equals(endpoint, "customer_zones", StringComparison.OrdinalIgnoreCase)) - return new[] { "customer_zones", "customer_zone" }; if (string.Equals(endpoint, "application_zones", StringComparison.OrdinalIgnoreCase)) - return new[] { "application_zones", "application_zone" }; if (string.Equals(endpoint, "vms", StringComparison.OrdinalIgnoreCase)) - return new[] { "vms", "vm", "virtual_machines", "systems", "system" }; return new[] { endpoint }; - } private static string TrimBody(string body) - { - if (body.Length > 400) - + { return body[..400] + "..."; + } return body; - } private sealed class FlexibleStringJsonConverter : JsonConverter - { - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (reader.TokenType == JsonTokenType.String) - return reader.GetString() ?? string.Empty; if (reader.TokenType == JsonTokenType.Number) - return reader.GetDouble().ToString(System.Globalization.CultureInfo.InvariantCulture); if (reader.TokenType == JsonTokenType.True) - return bool.TrueString; if (reader.TokenType == JsonTokenType.False) - return bool.FalseString; if (reader.TokenType == JsonTokenType.Null) - return string.Empty; using var doc = JsonDocument.ParseValue(ref reader); - return doc.RootElement.ToString(); - } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) - - => writer.WriteStringValue(value); - + => writer.WriteStringValue(value); } - } diff --git a/src/MaxInventory.Infrastructure/Http/InventoryHttpClientFactory.cs b/src/MaxInventory.Infrastructure/Http/InventoryHttpClientFactory.cs index 8b9fbe6..a9a1f5b 100644 --- a/src/MaxInventory.Infrastructure/Http/InventoryHttpClientFactory.cs +++ b/src/MaxInventory.Infrastructure/Http/InventoryHttpClientFactory.cs @@ -1,27 +1,19 @@ -using System.Net; -using MaxInventory.Core.Services; +using System.Net; using MaxInventory.Core.Settings; namespace MaxInventory.Infrastructure.Http { /// - /// Factory for creating an HttpClient configured with certificate authentication, - /// proxy settings, and the correct base URL for the inventory API. + /// Factory for creating an HttpClient configured with proxy settings + /// and the correct base URL for the inventory API. /// public static class InventoryHttpClientFactory { /// Creates a fully configured HttpClient for the inventory API. - public static HttpClient Create( - ICertificateProvider certificateProvider, - ApiSettings apiSettings, - ProxySettings proxySettings) + public static HttpClient Create(ApiSettings apiSettings, ProxySettings proxySettings) { var handler = new HttpClientHandler(); - //Attach client certificate for mutual TLS - var cert = certificateProvider.GetClientCertificate(); - handler.ClientCertificates.Add(cert); - //Configure proxy if enabled if (proxySettings.Enabled && !string.IsNullOrEmpty(proxySettings.Address)) { diff --git a/src/MaxInventory.Infrastructure/Http/NoOpInventoryApiAuthenticator.cs b/src/MaxInventory.Infrastructure/Http/NoOpInventoryApiAuthenticator.cs new file mode 100644 index 0000000..1e10250 --- /dev/null +++ b/src/MaxInventory.Infrastructure/Http/NoOpInventoryApiAuthenticator.cs @@ -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; + } +} diff --git a/src/MaxInventory.Web/Components/Pages/ContentTypePage.razor.cs b/src/MaxInventory.Web/Components/Pages/ContentTypePage.razor.cs index 9f6ac29..5a0a5b6 100644 --- a/src/MaxInventory.Web/Components/Pages/ContentTypePage.razor.cs +++ b/src/MaxInventory.Web/Components/Pages/ContentTypePage.razor.cs @@ -1,5 +1,6 @@ namespace MaxInventory.Web.Components.Pages; +using System.Security.Claims; using MaxInventory.Authentication.Abstractions; using MaxInventory.Core.Configuration; using MaxInventory.Core.Enums; @@ -92,7 +93,7 @@ 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); } @@ -222,8 +223,9 @@ public partial class ContentTypePage : ComponentBase .GetMethod(nameof(IInventoryApiClient.GetAllAsync))! .MakeGenericMethod(def.ModelType); + var principal = await GetCurrentUserAsync(); 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; var result = task.GetType().GetProperty("Result")!.GetValue(task); @@ -336,8 +338,9 @@ public partial class ContentTypePage : ComponentBase .GetMethod(nameof(IInventoryApiClient.CreateAsync))! .MakeGenericMethod(activeDefinition.ModelType); + var principal = await GetCurrentUserAsync(); 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; ToastService.ShowSuccess($"{activeDefinition.DisplayName} created successfully."); @@ -349,8 +352,9 @@ public partial class ContentTypePage : ComponentBase .GetMethod(nameof(IInventoryApiClient.UpdateAsync))! .MakeGenericMethod(activeDefinition.ModelType); + var principal = await GetCurrentUserAsync(); 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; ToastService.ShowSuccess($"{activeDefinition.DisplayName} updated successfully."); @@ -385,7 +389,8 @@ public partial class ContentTypePage : ComponentBase try { - await ApiClient.DeleteAsync(_definition.ApiEndpoint, idToDelete); + var principal = await GetCurrentUserAsync(); + await ApiClient.DeleteAsync(principal, _definition.ApiEndpoint, idToDelete); ToastService.ShowSuccess($"{_definition.DisplayName} deleted."); if (_selectedItem?.Id == idToDelete) _selectedItem = null; @@ -437,13 +442,18 @@ public partial class ContentTypePage : ComponentBase private async Task ResolvePermissionsAsync() { - var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); - var access = await PrincipalAccessEvaluator.EvaluateAsync(state.User); - + var principal = await GetCurrentUserAsync(); + var access = await PrincipalAccessEvaluator.EvaluateAsync(principal); _canView = access.CanView; _canEdit = access.CanEdit; _canDelete = access.CanDelete; } + private async Task GetCurrentUserAsync() + { + var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); + return state.User; + } + } diff --git a/src/MaxInventory.Web/Program.cs b/src/MaxInventory.Web/Program.cs index 2fc3877..4bba062 100644 --- a/src/MaxInventory.Web/Program.cs +++ b/src/MaxInventory.Web/Program.cs @@ -1,5 +1,7 @@ using MaxInventory.Authentication.Core; +using MaxInventory.Authentication.Configuration; using MaxInventory.Authentication.Extensions; +using MaxInventory.Core.Services; using MaxInventory.Infrastructure.Extensions; using MaxInventory.Web.Components; using MaxInventory.Web.Services; @@ -33,6 +35,14 @@ builder.Services.AddCascadingAuthenticationState(); builder.Services.AddInventoryServices(builder.Configuration); builder.Services.AddAuthentication(builder.Configuration); +if (string.Equals( + builder.Configuration[AuthEnvironment.AuthMode], + AuthModes.Cas, + StringComparison.OrdinalIgnoreCase)) +{ + builder.Services.AddScoped(); +} + builder.Services .AddOptions(CookieAuthenticationDefaults.AuthenticationScheme) .Configure((options, ticketStore) => diff --git a/src/MaxInventory.Web/Services/CasInventoryApiAuthenticator.cs b/src/MaxInventory.Web/Services/CasInventoryApiAuthenticator.cs new file mode 100644 index 0000000..4f620c3 --- /dev/null +++ b/src/MaxInventory.Web/Services/CasInventoryApiAuthenticator.cs @@ -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); + } +} diff --git a/src/MaxInventory.Web/appsettings.json b/src/MaxInventory.Web/appsettings.json index dc6d778..6aa21d4 100644 --- a/src/MaxInventory.Web/appsettings.json +++ b/src/MaxInventory.Web/appsettings.json @@ -8,9 +8,9 @@ "AllowedHosts": "*", "Api": { "BaseUrl": "https://directauth.max.gov/inventory", - "TimeoutSeconds": 30 + "TimeoutSeconds": 30, + "CasProxyTicketHeaderName": "X-CAS-Proxy-Ticket" }, - "Proxy": { "Enabled": true, "Address": "http://proxy.omb.gov:8080"