- 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:
@@ -0,0 +1,102 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using AMWD.Common.AspNetCore.BasicAuthentication;
|
||||
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.Attributes
|
||||
{
|
||||
/// <summary>
|
||||
/// A basic authentication as attribute to use for specific actions.
|
||||
/// </summary>
|
||||
public class BasicAuthenticationAttribute : ActionFilterAttribute
|
||||
{
|
||||
private readonly IServiceScopeFactory serviceScopeFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BasicAuthenticationAttribute"/> class.
|
||||
/// </summary>
|
||||
/// <param name="serviceScopeFactory">A service scope factory.</param>
|
||||
public BasicAuthenticationAttribute(IServiceScopeFactory serviceScopeFactory)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
using var scope = serviceScopeFactory.CreateScope();
|
||||
var logger = scope.ServiceProvider.GetService<ILogger<BasicAuthenticationAttribute>>();
|
||||
|
||||
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, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(Username) && !string.IsNullOrWhiteSpace(Password))
|
||||
{
|
||||
if (Username == credentials.First() && Password == credentials.Last())
|
||||
return;
|
||||
}
|
||||
|
||||
var validator = scope.ServiceProvider.GetService<IBasicAuthenticationValidator>();
|
||||
var principal = await validator?.ValidateAsync(credentials.First(), credentials.Last(), 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 = StatusCodes.Status401Unauthorized;
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status401Unauthorized);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ namespace AMWD.Common.AspNetCore.Attributes
|
||||
|
||||
if (MatchesIpAddress(ipAddress, remoteIpAddress))
|
||||
{
|
||||
context.Result = new ForbidResult();
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,7 @@ namespace AMWD.Common.AspNetCore.Attributes
|
||||
|
||||
if (MatchesIpAddress(child.Value, remoteIpAddress))
|
||||
{
|
||||
context.Result = new ForbidResult();
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -87,17 +87,24 @@ namespace AMWD.Common.AspNetCore.Attributes
|
||||
|
||||
private static bool MatchesIpAddress(string configIpAddress, IPAddress remoteIpAddress)
|
||||
{
|
||||
if (configIpAddress.Contains('/'))
|
||||
try
|
||||
{
|
||||
string[] ipNetworkParts = configIpAddress.Split('/');
|
||||
var ip = IPAddress.Parse(ipNetworkParts.First());
|
||||
int prefix = int.Parse(ipNetworkParts.Last());
|
||||
if (configIpAddress.Contains('/'))
|
||||
{
|
||||
string[] ipNetworkParts = configIpAddress.Split('/');
|
||||
var ip = IPAddress.Parse(ipNetworkParts.First());
|
||||
int prefix = int.Parse(ipNetworkParts.Last());
|
||||
|
||||
var net = new IPNetwork(ip, prefix);
|
||||
return net.Contains(remoteIpAddress);
|
||||
var net = new IPNetwork(ip, prefix);
|
||||
return net.Contains(remoteIpAddress);
|
||||
}
|
||||
|
||||
return IPAddress.Parse(configIpAddress).Equals(remoteIpAddress);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return IPAddress.Parse(configIpAddress).Equals(remoteIpAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ namespace AMWD.Common.AspNetCore.Attributes
|
||||
var section = configuration.GetSection(ConfigurationKey);
|
||||
if (!section.Exists())
|
||||
{
|
||||
context.Result = new ForbidResult();
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -81,22 +81,29 @@ namespace AMWD.Common.AspNetCore.Attributes
|
||||
}
|
||||
}
|
||||
|
||||
context.Result = new ForbidResult();
|
||||
context.Result = new StatusCodeResult(StatusCodes.Status403Forbidden);
|
||||
}
|
||||
|
||||
private static bool MatchesIpAddress(string configIpAddress, IPAddress remoteIpAddress)
|
||||
{
|
||||
if (configIpAddress.Contains('/'))
|
||||
try
|
||||
{
|
||||
string[] ipNetworkParts = configIpAddress.Split('/');
|
||||
var ip = IPAddress.Parse(ipNetworkParts.First());
|
||||
int prefix = int.Parse(ipNetworkParts.Last());
|
||||
if (configIpAddress.Contains('/'))
|
||||
{
|
||||
string[] ipNetworkParts = configIpAddress.Split('/');
|
||||
var ip = IPAddress.Parse(ipNetworkParts.First());
|
||||
int prefix = int.Parse(ipNetworkParts.Last());
|
||||
|
||||
var net = new IPNetwork(ip, prefix);
|
||||
return net.Contains(remoteIpAddress);
|
||||
var net = new IPNetwork(ip, prefix);
|
||||
return net.Contains(remoteIpAddress);
|
||||
}
|
||||
|
||||
return IPAddress.Parse(configIpAddress).Equals(remoteIpAddress);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return IPAddress.Parse(configIpAddress).Equals(remoteIpAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user