Refactor and expand REST action authentication support

Refactored authentication logic for REST actions to use a structured switch block, adding explicit support for ApiKey, BearerToken, JwtBearer, OAuth2, BasicAuth, and NTLM authentication types. Introduced dedicated HttpClient/Handler for NTLM with proper disposal. Improved extensibility, clarity, and resource management. Added IOptions and Options usage for configuration.
This commit is contained in:
2026-03-16 13:43:27 +01:00
parent b38d53248c
commit 87194df697

View File

@@ -1,9 +1,11 @@
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using ReC.Application.Common;
using ReC.Application.Common.Constants;
using ReC.Application.Common.Dto;
using ReC.Application.Common.Exceptions;
using ReC.Application.Common.Options;
using ReC.Application.Common.Procedures.InsertProcedure;
using ReC.Application.Results.Commands;
using ReC.Domain.Constants;
@@ -32,8 +34,6 @@ public class InvokeRecActionViewCommandHandler(
{
var action = request.Action;
using var http = clientFactory.CreateClient(Http.ClientName);
if (action.RestType is not RestType restType)
throw new DataIntegrityException(
$"Rec action could not be invoked because the RestType value is null. " +
@@ -50,6 +50,11 @@ public class InvokeRecActionViewCommandHandler(
foreach (var header in action.Headers)
httpReq.Headers.Add(header.Key, header.Value);
HttpClient? ntlmClient = null;
HttpClientHandler? ntlmHandler = null;
try
{
switch (action.EndpointAuthType)
{
case EndpointAuthType.NoAuth:
@@ -113,7 +118,12 @@ public class InvokeRecActionViewCommandHandler(
endpointAuthPassword,
action.EndpointAuthDomain);
var credentialCache = new CredentialCache { { httpReq.RequestUri!, "NTLM", credentials } };
httpReq.Options.Set(new HttpRequestOptionsKey<CredentialCache>("Credentials"), credentialCache);
ntlmHandler = new HttpClientHandler
{
Credentials = credentialCache,
UseDefaultCredentials = false
};
ntlmClient = new HttpClient(ntlmHandler);
}
break;
@@ -131,6 +141,7 @@ public class InvokeRecActionViewCommandHandler(
);
}
using var http = ntlmClient ?? clientFactory.CreateClient(Http.ClientName);
using var response = await http.SendAsync(httpReq, cancel);
var resBody = await response.Content.ReadAsStringAsync(cancel);
var resHeaders = response.Headers.ToDictionary();
@@ -147,6 +158,11 @@ public class InvokeRecActionViewCommandHandler(
return response.IsSuccessStatusCode;
}
finally
{
ntlmHandler?.Dispose();
}
}
private static HttpRequestMessage CreateHttpRequestMessage(RestType restType, string? endpointUri)
{