CAS
This commit is contained in:
@@ -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
|
||||
{
|
||||
@@ -11,37 +12,33 @@ namespace MaxInventory.Core.Services
|
||||
/// <summary>
|
||||
/// Retrieves all records of the specified type from the given endpoint.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default) where T : class, IInventoryEntity;
|
||||
Task<List<T>> GetAllAsync<T>(ClaimsPrincipal principal, string endpoint, CancellationToken ct = default)
|
||||
where T : class, IInventoryEntity;
|
||||
|
||||
/// <summary>
|
||||
/// Creates new record at the given endpoint. Returns the server-assigned ID.
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="entity"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default) where T : class, IInventoryEntity;
|
||||
Task<ApiCreateResponse> CreateAsync<T>(
|
||||
ClaimsPrincipal principal,
|
||||
string endpoint,
|
||||
T entity,
|
||||
CancellationToken ct = default)
|
||||
where T : class, IInventoryEntity;
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing record by ID at the given endpoint (HTTP PUT).
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="entity"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default) where T : class, IInventoryEntity;
|
||||
Task UpdateAsync<T>(
|
||||
ClaimsPrincipal principal,
|
||||
string endpoint,
|
||||
int id,
|
||||
T entity,
|
||||
CancellationToken ct = default)
|
||||
where T : class, IInventoryEntity;
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a record by ID at the given endpoint.
|
||||
/// </summary>
|
||||
/// <param name="endpoint"></param>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
Task DeleteAsync(string endpoint, int id, CancellationToken ct = default);
|
||||
Task DeleteAsync(ClaimsPrincipal principal, string endpoint, int id, CancellationToken ct = default);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,5 +15,16 @@
|
||||
/// HTTP request timeout in seconds. Default is 30.
|
||||
/// </summary>
|
||||
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 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
|
||||
{
|
||||
///<summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IServiceCollection AddInventoryServices(
|
||||
this IServiceCollection services,
|
||||
@@ -63,14 +62,11 @@ namespace MaxInventory.Infrastructure.Extensions
|
||||
}
|
||||
|
||||
//Http Client
|
||||
services.AddSingleton<HttpClient>(sp =>
|
||||
{
|
||||
var certProvider = sp.GetRequiredService<ICertificateProvider>();
|
||||
return InventoryHttpClientFactory.Create(certProvider, apiSettings, proxySettings);
|
||||
});
|
||||
services.AddSingleton(sp => InventoryHttpClientFactory.Create(apiSettings, proxySettings));
|
||||
|
||||
// API Client
|
||||
services.AddSingleton<IInventoryApiClient, InventoryApiClient>();
|
||||
services.AddScoped<IInventoryApiAuthenticator, NoOpInventoryApiAuthenticator>();
|
||||
services.AddScoped<IInventoryApiClient, InventoryApiClient>();
|
||||
|
||||
// Serializer
|
||||
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.Json;
|
||||
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
using MaxInventory.Core.Models;
|
||||
|
||||
using MaxInventory.Core.Services;
|
||||
|
||||
/// <summary>
|
||||
|
||||
/// 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.
|
||||
|
||||
/// </summary>
|
||||
|
||||
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());
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public async Task<List<T>> GetAllAsync<T>(string endpoint, CancellationToken ct = default)
|
||||
|
||||
where T : class, IInventoryEntity
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<List<T>> GetAllAsync<T>(
|
||||
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<List<T>>(json, _jsonOptions) ?? new List<T>();
|
||||
|
||||
// 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)}");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public async Task<ApiCreateResponse> CreateAsync<T>(string endpoint, T entity, CancellationToken ct = default)
|
||||
|
||||
where T : class, IInventoryEntity
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ApiCreateResponse> CreateAsync<T>(
|
||||
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<ApiCreateResponse>(responseJson, _jsonOptions)
|
||||
|
||||
?? throw new InvalidOperationException("API returned null response on create.");
|
||||
|
||||
?? throw new InvalidOperationException("API returned null response on create.");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public async Task UpdateAsync<T>(string endpoint, int id, T entity, CancellationToken ct = default)
|
||||
|
||||
where T : class, IInventoryEntity
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task UpdateAsync<T>(
|
||||
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);
|
||||
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
public async Task DeleteAsync(string endpoint, int id, CancellationToken ct = default)
|
||||
|
||||
/// <inheritdoc />
|
||||
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<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(
|
||||
|
||||
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<string> 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<string>
|
||||
|
||||
{
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
using System.Net;
|
||||
using MaxInventory.Core.Services;
|
||||
using System.Net;
|
||||
using MaxInventory.Core.Settings;
|
||||
|
||||
namespace MaxInventory.Infrastructure.Http
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static class InventoryHttpClientFactory
|
||||
{
|
||||
///<summary> Creates a fully configured HttpClient for the inventory API.</summary>
|
||||
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))
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
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<ClaimsPrincipal> GetCurrentUserAsync()
|
||||
{
|
||||
var state = await AuthenticationStateProvider.GetAuthenticationStateAsync();
|
||||
return state.User;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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<IInventoryApiAuthenticator, CasInventoryApiAuthenticator>();
|
||||
}
|
||||
|
||||
builder.Services
|
||||
.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.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);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user