BasicAuthentication als Attribut für Actions
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using System;
|
||||
using System.Net.Http.Headers;
|
||||
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 AMWD.Common.AspNetCore.BasicAuthentication
|
||||
{
|
||||
/// <summary>
|
||||
/// Implements the <see cref="AuthenticationHandler{TOptions}"/> for Basic Authentication.
|
||||
/// </summary>
|
||||
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
private readonly ILogger logger;
|
||||
private readonly IBasicAuthenticationValidator validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BasicAuthenticationHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="options">The authentication scheme options.</param>
|
||||
/// <param name="loggerFactory">The logger factory.</param>
|
||||
/// <param name="encoder">The URL encoder.</param>
|
||||
/// <param name="clock">The system clock.</param>
|
||||
/// <param name="validator">An basic autentication validator implementation.</param>
|
||||
public BasicAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory loggerFactory, UrlEncoder encoder, ISystemClock clock, IBasicAuthenticationValidator validator)
|
||||
: base(options, loggerFactory, encoder, clock)
|
||||
{
|
||||
logger = loggerFactory.CreateLogger<BasicAuthenticationHandler>();
|
||||
this.validator = validator;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
var endpoint = Context.GetEndpoint();
|
||||
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
|
||||
return AuthenticateResult.NoResult();
|
||||
|
||||
if (!Request.Headers.ContainsKey("Authorization"))
|
||||
return AuthenticateResult.Fail("Authorization header missing");
|
||||
|
||||
ClaimsPrincipal principal;
|
||||
try
|
||||
{
|
||||
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
|
||||
string plain = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter));
|
||||
string[] credentials = plain.Split(':', 2);
|
||||
|
||||
var ipAddress = Context.GetRemoteIpAddress();
|
||||
principal = await validator.ValidateAsync(credentials[0], credentials[1], ipAddress);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"Handling the Basic Authentication failed: {ex.Message}");
|
||||
return AuthenticateResult.Fail("Authorization header invalid");
|
||||
}
|
||||
|
||||
if (principal == null)
|
||||
return AuthenticateResult.Fail("Invalid credentials");
|
||||
|
||||
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
||||
return AuthenticateResult.Success(ticket);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace AMWD.Common.AspNetCore.BasicAuthentication
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface representing the validation of a basic authentication.
|
||||
/// </summary>
|
||||
public interface IBasicAuthenticationValidator
|
||||
{
|
||||
/// <summary>
|
||||
/// Validates a username and password for Basic Authentication.
|
||||
/// </summary>
|
||||
/// <param name="username">A username.</param>
|
||||
/// <param name="password">A password.</param>
|
||||
/// <param name="remoteAddress">The remote client's IP address.</param>
|
||||
/// <returns>The validated user principal or <c>null</c>.</returns>
|
||||
Task<ClaimsPrincipal> ValidateAsync(string username, string password, IPAddress remoteAddress);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user