1
0
Files
common/AMWD.Common.AspNetCore/Middlewares/BasicAuthMiddleware.cs
2021-10-22 21:12:32 +02:00

69 lines
2.2 KiB
C#

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Implements a basic authentication.
/// </summary>
public class BasicAuthMiddleware
{
private readonly RequestDelegate next;
private readonly string realm;
private readonly Func<string, string, bool> userPasswordAuth;
/// <summary>
/// Initializes a new instance of the <see cref="BasicAuthMiddleware"/> class.
/// </summary>
/// <param name="next">The following delegate in the process chain.</param>
/// <param name="realm">The realm to display when requesting for credentials.</param>
/// <param name="userPasswordAuth">The function <c>(user, passwd) => result</c> to validate username and password.</param>
public BasicAuthMiddleware(RequestDelegate next, string realm, Func<string, string, bool> userPasswordAuth)
{
this.next = next;
this.realm = realm;
this.userPasswordAuth = userPasswordAuth;
}
/// <summary>
/// The delegate invokation.
/// Performs the authentication check.
/// </summary>
/// <param name="httpContext">The corresponding HTTP context.</param>
/// <returns>An awaitable task.</returns>
public async Task InvokeAsync(HttpContext httpContext)
{
if (httpContext.Request.Headers.TryGetValue("Authorization", out var authHeader)
&& ((string)authHeader).StartsWith("Basic "))
{
string encoded = ((string)authHeader).Split(' ', StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
string[] parts = decoded.Split(':');
if (parts.Length >= 2)
{
string username = parts[0].Trim().ToLower();
string password = parts[1].Trim();
if (userPasswordAuth(username, password))
{
await next.Invoke(httpContext);
return;
}
}
}
httpContext.Response.Headers["WWW-Authenticate"] = "Basic";
if (!string.IsNullOrWhiteSpace(realm))
{
httpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{realm}\"";
}
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
}
}
}