- BasicAuthenticationAttribute sets the HttpContext.User property when successfully validated. - Moved BasicAuthenticationAttribute from ActionFilter to IAsyncAuthorizationFilter. - TimeSpan.ToShortString() is now capable of negative values.
113 lines
4.0 KiB
C#
113 lines
4.0 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Net.Http.Headers;
|
|
using System.Security.Claims;
|
|
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 Microsoft.AspNetCore.Authorization
|
|
{
|
|
/// <summary>
|
|
/// A basic authentication as attribute to use for specific actions.
|
|
/// </summary>
|
|
public class BasicAuthenticationAttribute : Attribute, IAsyncAuthorizationFilter
|
|
{
|
|
/// <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 async Task OnAuthorizationAsync(AuthorizationFilterContext context)
|
|
{
|
|
var logger = context.HttpContext.RequestServices.GetService<ILogger<BasicAuthenticationAttribute>>();
|
|
try
|
|
{
|
|
var validatorResult = await TrySetHttpUser(context);
|
|
bool isAllowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
|
|
if (isAllowAnonymous)
|
|
return;
|
|
|
|
if (!context.HttpContext.Request.Headers.ContainsKey("Authorization"))
|
|
{
|
|
SetAuthenticateRequest(context);
|
|
return;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
if (validatorResult == null)
|
|
SetAuthenticateRequest(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger?.LogError(ex, $"Failed to execute the basic authentication attribute: {ex.InnerException?.Message ?? ex.Message}");
|
|
context.Result = new StatusCodeResult(StatusCodes.Status500InternalServerError);
|
|
}
|
|
}
|
|
|
|
private void SetAuthenticateRequest(AuthorizationFilterContext 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);
|
|
}
|
|
|
|
private async Task<ClaimsPrincipal> TrySetHttpUser(AuthorizationFilterContext context)
|
|
{
|
|
var logger = context.HttpContext.RequestServices.GetService<ILogger<BasicAuthenticationAttribute>>();
|
|
try
|
|
{
|
|
if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
|
|
{
|
|
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);
|
|
|
|
var validator = context.HttpContext.RequestServices.GetService<IBasicAuthenticationValidator>();
|
|
var result = await validator?.ValidateAsync(credentials.First(), credentials.Last(), context.HttpContext.GetRemoteIpAddress());
|
|
if (result != null)
|
|
context.HttpContext.User = result;
|
|
|
|
return result;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger?.LogError(ex, $"Using validator to get HTTP user failed: {ex.InnerException?.Message ?? ex.Message}");
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
}
|