1
0
Files
common/AMWD.Common.AspNetCore/BasicAuthentication/BasicAuthenticationMiddleware.cs
Andreas Mueller 33c2b9336f - Fixed problem with ForbidResult without having an authentication schema defined.
Now only HTTP Status 403 (Forbid) is returned.
- BasicAuthenticationAttribute is now in namespace AMWD.Common.AspNetCore.Attributes.
2022-06-22 22:53:34 +02:00

75 lines
2.4 KiB
C#

using System;
using System.Linq;
using System.Net.Http.Headers;
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 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)
{
this.next = next;
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.ContainsKey("Authorization"))
{
SetAuthenticateRequest(httpContext, validator.Realm);
return;
}
try
{
var authHeader = AuthenticationHeaderValue.Parse(httpContext.Request.Headers["Authorization"]);
byte[] decoded = Convert.FromBase64String(authHeader.Parameter);
string plain = Encoding.UTF8.GetString(decoded);
string[] credentials = plain.Split(':', 2, StringSplitOptions.RemoveEmptyEntries);
var principal = await validator.ValidateAsync(credentials.First(), credentials.Last(), httpContext.GetRemoteIpAddress());
if (principal == null)
{
SetAuthenticateRequest(httpContext, validator.Realm);
return;
}
await next.Invoke(httpContext);
}
catch
{
SetAuthenticateRequest(httpContext, validator.Realm);
}
}
private static void SetAuthenticateRequest(HttpContext httpContext, string realm)
{
httpContext.Response.Headers["WWW-Authenticate"] = "Basic";
if (!string.IsNullOrWhiteSpace(realm))
httpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{realm.Replace("\"", "")}\"";
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
}
}
}