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,101 @@
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace AMWD.Common.AspNetCore.BasicAuthentication
{
/// <summary>
/// A basic authentication as attribute to use for specific actions.
/// </summary>
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
private readonly ILogger<BasicAuthenticationAttribute> logger;
private readonly IServiceScopeFactory serviceScopeFactory;
/// <summary>
/// Initializes a new instance of the <see cref="BasicAuthenticationAttribute"/> class.
/// </summary>
/// <param name="logger">A logger.</param>
/// <param name="serviceScopeFactory">A service scope factory.</param>
public BasicAuthenticationAttribute(ILogger<BasicAuthenticationAttribute> logger, IServiceScopeFactory serviceScopeFactory)
{
this.logger = logger;
this.serviceScopeFactory = serviceScopeFactory;
}
/// <summary>
/// Gets or sets a username to validate.
/// </summary>
public string Username { get; set; }
/// <summary>
/// Gets or sets a password to validate.
/// </summary>
public string Password { get; set; }
/// <summary>
/// Gets or sets a realm used on authentication header.
/// </summary>
public string Realm { get; set; }
/// <inheritdoc/>
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
await DoValidation(context);
await base.OnActionExecutionAsync(context, next);
}
private async Task DoValidation(ActionExecutingContext context)
{
if (context.Result != null)
return;
if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
{
SetAuthenticateRequest(context);
return;
}
try
{
var authHeader = AuthenticationHeaderValue.Parse(context.HttpContext.Request.Headers["Authorization"]);
byte[] decoded = Convert.FromBase64String(authHeader.Parameter);
string plain = Encoding.UTF8.GetString(decoded);
string[] credentials = plain.Split(':', 2);
if (!string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password))
{
if (Username == credentials[0] && Password == credentials[1])
return;
}
using var scope = serviceScopeFactory.CreateScope();
var validator = scope.ServiceProvider.GetService<IBasicAuthenticationValidator>();
var principal = await validator?.ValidateAsync(credentials[0], credentials[1], context.HttpContext.GetRemoteIpAddress());
if (principal == null)
SetAuthenticateRequest(context);
}
catch (Exception ex)
{
logger.LogError(ex, $"Failed to execute the basic authentication attribute: {ex.Message}");
context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
private void SetAuthenticateRequest(ActionExecutingContext context)
{
context.HttpContext.Response.Headers["WWW-Authenticate"] = "Basic";
if (!string.IsNullOrWhiteSpace(Realm))
context.HttpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{Realm.Replace("\"", "")}\"";
context.Result = new UnauthorizedResult();
}
}
}

View File

@@ -4,12 +4,13 @@ using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
namespace AMWD.Common.AspNetCore.BasicAuthentication
{
/// <summary>
/// Implements the <see cref="AuthenticationHandler{TOptions}"/> for Basic Authentication.

View File

@@ -2,29 +2,30 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Http
namespace AMWD.Common.AspNetCore.BasicAuthentication
{
/// <summary>
/// Implements a basic authentication.
/// </summary>
public class BasicAuthMiddleware
public class BasicAuthenticationMiddleware
{
private readonly RequestDelegate next;
private readonly string realm;
private readonly Func<string, string, bool> userPasswordAuth;
private readonly IBasicAuthenticationValidator validator;
/// <summary>
/// Initializes a new instance of the <see cref="BasicAuthMiddleware"/> class.
/// 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="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)
/// <param name="validator">A basic authentication validator.</param>
public BasicAuthenticationMiddleware(RequestDelegate next, string realm, IBasicAuthenticationValidator validator)
{
this.next = next;
this.realm = realm;
this.userPasswordAuth = userPasswordAuth;
this.validator = validator;
}
/// <summary>
@@ -41,18 +42,13 @@ namespace Microsoft.AspNetCore.Http
string encoded = ((string)authHeader).Split(' ', StringSplitOptions.RemoveEmptyEntries).LastOrDefault() ?? "";
string decoded = Encoding.UTF8.GetString(Convert.FromBase64String(encoded));
string[] parts = decoded.Split(':');
string[] parts = decoded.Split(':', 2);
if (parts.Length >= 2)
var principal = validator.ValidateAsync(parts[0], parts[1], httpContext.GetRemoteIpAddress());
if (principal != null)
{
string username = parts[0].Trim().ToLower();
string password = parts[1].Trim();
if (userPasswordAuth(username, password))
{
await next.Invoke(httpContext);
return;
}
await next.Invoke(httpContext);
return;
}
}

View File

@@ -2,7 +2,7 @@
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authentication
namespace AMWD.Common.AspNetCore.BasicAuthentication
{
/// <summary>
/// Interface representing the validation of a basic authentication.

View File

@@ -9,12 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- CHANGELOG
- `HtmlHelper.IsDarkColor` to classify a color as dark or light one (by luminance)
- `ReadLine` and `ReadLineAsync` as `StreamExtensions`
- `BasicAuthenticationHandler` to use instead of other handlers (instead of e.g. CookieAuthentication)
- `BasicAuthenticationAttribute` to restrict single actions
### Changed
- Unit-Tests enhanced
- Unit-Tests excluded from code coverage calcualtion
- Updated NuGet package `NetRevisionTask`
- Changed NuGet package `DnsClient` to `DNS`
## [v1.1.0](https://git.am-wd.de/AM.WD/common/compare/v1.0.2...v1.1.0) - 2021-11-22