- 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.
This commit is contained in:
@@ -1,102 +0,0 @@
|
||||
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.HttpContext.Response.StatusCode = 401;
|
||||
context.Result = new UnauthorizedResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
@@ -50,10 +51,10 @@ namespace AMWD.Common.AspNetCore.BasicAuthentication
|
||||
{
|
||||
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
|
||||
string plain = Encoding.UTF8.GetString(Convert.FromBase64String(authHeader.Parameter));
|
||||
string[] credentials = plain.Split(':', 2);
|
||||
string[] credentials = plain.Split(':', 2, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
var ipAddress = Context.GetRemoteIpAddress();
|
||||
principal = await validator.ValidateAsync(credentials[0], credentials[1], ipAddress);
|
||||
principal = await validator.ValidateAsync(credentials.First(), credentials.Last(), ipAddress);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
@@ -33,25 +34,39 @@ namespace AMWD.Common.AspNetCore.BasicAuthentication
|
||||
/// <returns>An awaitable task.</returns>
|
||||
public async Task InvokeAsync(HttpContext httpContext)
|
||||
{
|
||||
if (httpContext.Request.Headers.TryGetValue("Authorization", out var authHeader)
|
||||
&& ((string)authHeader).StartsWith("Basic "))
|
||||
if (!httpContext.Request.Headers.ContainsKey("Authorization"))
|
||||
{
|
||||
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;
|
||||
}
|
||||
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(validator.Realm))
|
||||
httpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{validator.Realm}\"";
|
||||
if (!string.IsNullOrWhiteSpace(realm))
|
||||
httpContext.Response.Headers["WWW-Authenticate"] += $" realm=\"{realm.Replace("\"", "")}\"";
|
||||
|
||||
httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user