1
0

Updated to C# 12

This commit is contained in:
2024-01-14 13:10:33 +01:00
parent 9cd1344266
commit 27cd54fb30
51 changed files with 637 additions and 379 deletions

View File

@@ -11,21 +11,15 @@ namespace AMWD.Common.AspNetCore.Security.BasicAuthentication
/// <summary>
/// Implements a basic authentication.
/// </summary>
public class BasicAuthenticationMiddleware
/// <remarks>
/// Initializes a new instance of the <see cref="BasicAuthenticationMiddleware"/> class.
/// </remarks>
/// <param name="next">The following delegate in the process chain.</param>
/// <param name="validator">A basic authentication validator.</param>
public class BasicAuthenticationMiddleware(RequestDelegate next, IBasicAuthenticationValidator validator)
{
private readonly RequestDelegate _next;
private readonly IBasicAuthenticationValidator _validator;
/// <summary>
/// Initializes a new instance of the <see cref="BasicAuthenticationMiddleware"/> class.
/// </summary>
/// <param name="next">The following delegate in the process chain.</param>
/// <param name="validator">A basic authentication validator.</param>
public BasicAuthenticationMiddleware(RequestDelegate next, IBasicAuthenticationValidator validator)
{
_next = next;
_validator = validator;
}
private readonly RequestDelegate _next = next;
private readonly IBasicAuthenticationValidator _validator = validator;
/// <summary>
/// The delegate invokation.
@@ -35,15 +29,27 @@ namespace AMWD.Common.AspNetCore.Security.BasicAuthentication
/// <returns>An awaitable task.</returns>
public async Task InvokeAsync(HttpContext httpContext)
{
#if NET8_0_OR_GREATER
if (!httpContext.Request.Headers.TryGetValue("Authorization", out var authHeaderValue))
{
SetAuthenticateRequest(httpContext, _validator.Realm);
return;
}
#else
if (!httpContext.Request.Headers.ContainsKey("Authorization"))
{
SetAuthenticateRequest(httpContext, _validator.Realm);
return;
}
#endif
try
{
#if NET8_0_OR_GREATER
var authHeader = AuthenticationHeaderValue.Parse(authHeaderValue);
#else
var authHeader = AuthenticationHeaderValue.Parse(httpContext.Request.Headers["Authorization"]);
#endif
byte[] decoded = Convert.FromBase64String(authHeader.Parameter);
string plain = Encoding.UTF8.GetString(decoded);
@@ -70,9 +76,9 @@ namespace AMWD.Common.AspNetCore.Security.BasicAuthentication
private static void SetAuthenticateRequest(HttpContext httpContext, string realm)
{
httpContext.Response.Headers["WWW-Authenticate"] = "Basic";
httpContext.Response.Headers.WWWAuthenticate = "Basic";
if (!string.IsNullOrWhiteSpace(realm))
httpContext.Response.Headers["WWW-Authenticate"] = $"Basic realm=\"{realm.Replace("\"", "")}\"";
httpContext.Response.Headers.WWWAuthenticate = $"Basic realm=\"{realm.Replace("\"", "")}\"";
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
}