1
0

DNS Auflösung bei E-Mail Adressen: DNS Client getauscht, BasicAuthenticationHandler implementiert.

This commit is contained in:
2021-12-21 22:26:58 +01:00
parent e5b9959d8e
commit 7a71bd91d5
5 changed files with 120 additions and 33 deletions

View File

@@ -35,30 +35,8 @@
<None Include="../icon.png" Pack="true" PackagePath="/" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.1.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.HttpOverrides" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor" Version="2.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.TagHelpers" Version="2.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="2.0.4" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.1" />
<PackageReference Include="Unclassified.DeepConvert" Version="1.3.0" />
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.2">

View File

@@ -0,0 +1,70 @@
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.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Authentication
{
/// <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);
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Authentication
{
/// <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);
}
}

View File

@@ -36,7 +36,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="DnsClient" Version="1.5.0" />
<PackageReference Include="Dns" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.1" />
<PackageReference Include="Unclassified.DeepConvert" Version="1.3.0" />
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.2">

View File

@@ -5,7 +5,8 @@ using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using DnsClient;
using DNS.Client;
using DNS.Protocol;
namespace System
{
@@ -148,10 +149,10 @@ namespace System
/// You can enhance the check by requesting the MX record of the domain.
/// </remarks>
/// <param name="email">The email address as string to validate.</param>
/// <param name="checkRecordExists">A value indicating whether to resolve a MX record.</param>
/// <param name="checkRecordExists">A value indicating whether to resolve a MX record (Google DNS is used).</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, bool checkRecordExists = false)
=> email.IsValidEmailAddress(checkRecordExists ? new LookupClient() : null);
=> email.IsValidEmailAddress(checkRecordExists ? new[] { new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53) } : null);
/// <summary>
/// Checks whether the given <see cref="string"/> is a valid <see cref="MailAddress"/>.
@@ -163,19 +164,36 @@ namespace System
/// <param name="nameservers">A list of <see cref="IPEndPoint"/>s of nameservers.</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, IEnumerable<IPEndPoint> nameservers)
=> email.IsValidEmailAddress(new LookupClient(nameservers.ToArray()));
private static bool IsValidEmailAddress(this string email, LookupClient lookupClient)
{
try
{
var mailAddress = new MailAddress(email);
bool isValid = mailAddress.Address == email;
if (isValid && lookupClient != null)
if (isValid && nameservers != null)
{
var result = lookupClient.Query(mailAddress.Host, QueryType.MX);
isValid &= result.Answers.MxRecords().Any();
bool exists = false;
foreach (var nameserver in nameservers)
{
var clientRequest = new ClientRequest(nameserver) { RecursionDesired = true };
clientRequest.Questions.Add(new Question(Domain.FromString(mailAddress.Host), RecordType.MX));
var response = clientRequest.Resolve()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
if (response.ResponseCode != ResponseCode.NoError)
continue;
exists = response.AnswerRecords
.Where(r => r.Type == RecordType.MX)
.Any();
break;
}
isValid &= exists;
}
return isValid;