1
0

BasicAuthentication als Attribut für Actions

This commit is contained in:
2021-12-21 23:22:28 +01:00
parent 7a71bd91d5
commit 2206585652
5 changed files with 120 additions and 19 deletions

View File

@@ -0,0 +1,64 @@
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace AMWD.Common.AspNetCore.BasicAuthentication
{
/// <summary>
/// Implements a basic authentication.
/// </summary>
public class BasicAuthenticationMiddleware
{
private readonly RequestDelegate next;
private readonly string realm;
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="realm">The realm to display when requesting for credentials.</param>
/// <param name="validator">A basic authentication validator.</param>
public BasicAuthenticationMiddleware(RequestDelegate next, string realm, IBasicAuthenticationValidator validator)
{
this.next = next;
this.realm = realm;
this.validator = validator;
}
/// <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(':', 2);
var principal = validator.ValidateAsync(parts[0], parts[1], httpContext.GetRemoteIpAddress());
if (principal != null)
{
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;
}
}
}