Init
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace maintenance.Authentication.Abstractions;
|
||||
|
||||
public interface IAuthProvider
|
||||
{
|
||||
string Mode { get; }
|
||||
|
||||
AuthenticationBuilder Configure(
|
||||
AuthenticationBuilder builder,
|
||||
IConfiguration configuration);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
using maintenance.Authentication.Core;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace maintenance.Authentication.Abstractions;
|
||||
|
||||
public interface IIdentityContextFactory
|
||||
{
|
||||
IdentityContext Create(ClaimsPrincipal principal);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace maintenance.Authentication.Configuration;
|
||||
|
||||
public static class AuthEnvironment
|
||||
{
|
||||
public const string AuthMode = "AUTH_MODE";
|
||||
public const string AdminGroups = "AUTH_ADMIN_GROUPS";
|
||||
|
||||
public const string AdfsMetadataAddress = "ADFS_METADATA_ADDRESS";
|
||||
public const string AdfsRealm = "ADFS_WTRELM";
|
||||
public const string AdfsReply = "ADFS_WREPLY";
|
||||
public const string AdfsCallbackPath = "ADFS_CALLBACK_PATH";
|
||||
public const string AdfsHomeRealm = "ADFS_WHR";
|
||||
public const string AdfsAuthType = "ADFS_WAUTH";
|
||||
public const string AdfsValidIssuers = "ADFS_VALID_ISSUERS";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace maintenance.Authentication.Configuration;
|
||||
|
||||
public static class AuthModes
|
||||
{
|
||||
public const string WsFed = "WSFED";
|
||||
public const string Oidc = "OIDC";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
using maintenance.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace maintenance.Authentication.Core;
|
||||
|
||||
public sealed class AdminRoleClaimsTransformation : IClaimsTransformation
|
||||
{
|
||||
private static readonly string[] GroupClaimTypes =
|
||||
{
|
||||
"groups",
|
||||
"group",
|
||||
ClaimTypes.GroupSid,
|
||||
"http://schemas.xmlsoap.org/claims/Group"
|
||||
};
|
||||
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public AdminRoleClaimsTransformation(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
|
||||
{
|
||||
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
if (identity.Claims.Any(c => c.Type == ClaimTypes.Role && c.Value == AuthRoles.Admin))
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
var configuredGroups = (_configuration[AuthEnvironment.AdminGroups] ?? string.Empty)
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
if (configuredGroups.Length == 0)
|
||||
{
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
|
||||
var principalGroups = identity.Claims
|
||||
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(c => c.Value);
|
||||
|
||||
var isAdmin = principalGroups.Any(group =>
|
||||
configuredGroups.Contains(group, StringComparer.OrdinalIgnoreCase));
|
||||
|
||||
if (isAdmin)
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.Role, AuthRoles.Admin));
|
||||
}
|
||||
|
||||
return Task.FromResult(principal);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace maintenance.Authentication.Core;
|
||||
|
||||
public static class AuthRoles
|
||||
{
|
||||
public const string Admin = "Admin";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace maintenance.Authentication.Core;
|
||||
|
||||
public sealed class IdentityContext
|
||||
{
|
||||
public required string UserId { get; init; }
|
||||
public required string DisplayName { get; init; }
|
||||
public required IReadOnlyCollection<string> Groups { get; init; }
|
||||
public required IReadOnlyCollection<string> Roles { get; init; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using maintenance.Authentication.Abstractions;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace maintenance.Authentication.Core;
|
||||
|
||||
public sealed class IdentityContextFactory : IIdentityContextFactory
|
||||
{
|
||||
private static readonly string[] GroupClaimTypes =
|
||||
{
|
||||
"groups",
|
||||
"group",
|
||||
ClaimTypes.GroupSid,
|
||||
"http://schemas.xmlsoap.org/claims/Group"
|
||||
};
|
||||
|
||||
public IdentityContext Create(ClaimsPrincipal principal)
|
||||
{
|
||||
var groups = principal.Claims
|
||||
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
|
||||
.Select(c => c.Value)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var roles = principal.Claims
|
||||
.Where(c => c.Type == ClaimTypes.Role)
|
||||
.Select(c => c.Value)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var userId = principal.FindFirstValue(ClaimTypes.NameIdentifier)
|
||||
?? principal.FindFirstValue("sub")
|
||||
?? principal.Identity?.Name
|
||||
?? "unknown";
|
||||
|
||||
var displayName = principal.FindFirstValue(ClaimTypes.Name)
|
||||
?? principal.Identity?.Name
|
||||
?? userId;
|
||||
|
||||
return new IdentityContext
|
||||
{
|
||||
UserId = userId,
|
||||
DisplayName = displayName,
|
||||
Groups = groups,
|
||||
Roles = roles
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
using maintenance.Authentication.Abstractions;
|
||||
using maintenance.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.WsFederation;
|
||||
using Microsoft.IdentityModel.Protocols.WsFederation;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.IdentityModel.Tokens.Saml;
|
||||
|
||||
namespace maintenance.Authentication.Providers.AdfsWsFed;
|
||||
|
||||
public sealed class AdfsWsFedAuthProvider : IAuthProvider
|
||||
{
|
||||
public const string Scheme = WsFederationDefaults.AuthenticationScheme;
|
||||
|
||||
public string Mode => AuthModes.WsFed;
|
||||
|
||||
AuthenticationBuilder IAuthProvider.Configure(
|
||||
AuthenticationBuilder builder,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
var metadataAddress = configuration[AuthEnvironment.AdfsMetadataAddress];
|
||||
var realm = configuration[AuthEnvironment.AdfsRealm];
|
||||
var callbackPath = configuration[AuthEnvironment.AdfsCallbackPath] ?? "/signin-wsfed";
|
||||
var replyUrl = configuration[AuthEnvironment.AdfsReply];
|
||||
var homeRealm = configuration[AuthEnvironment.AdfsHomeRealm];
|
||||
var authType = configuration[AuthEnvironment.AdfsAuthType];
|
||||
var configuredValidIssuers = configuration[AuthEnvironment.AdfsValidIssuers];
|
||||
|
||||
if (string.IsNullOrWhiteSpace(metadataAddress))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Missing required configuration: {AuthEnvironment.AdfsMetadataAddress}");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(realm))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Missing required configuration: {AuthEnvironment.AdfsRealm}");
|
||||
}
|
||||
|
||||
var validIssuers = configuredValidIssuers?
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(v => !string.IsNullOrWhiteSpace(v))
|
||||
.ToArray() ?? [];
|
||||
|
||||
if (validIssuers.Length == 0 && Uri.TryCreate(metadataAddress, UriKind.Absolute, out var metadataUri))
|
||||
{
|
||||
validIssuers = [$"{metadataUri.Scheme}://{metadataUri.Authority}/adfs/services/trust"];
|
||||
}
|
||||
|
||||
return builder.AddWsFederation(options =>
|
||||
{
|
||||
options.MetadataAddress = metadataAddress;
|
||||
options.Wtrealm = realm;
|
||||
options.CallbackPath = callbackPath;
|
||||
options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(replyUrl))
|
||||
{
|
||||
options.Wreply = replyUrl;
|
||||
}
|
||||
|
||||
options.TokenHandlers.Clear();
|
||||
options.TokenHandlers.Add(new CustomSamlSecurityTokenHandler());
|
||||
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidIssuers = validIssuers
|
||||
};
|
||||
|
||||
options.Events = new WsFederationEvents
|
||||
{
|
||||
OnRedirectToIdentityProvider = context =>
|
||||
{
|
||||
context.ProtocolMessage ??= new WsFederationMessage();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(replyUrl))
|
||||
{
|
||||
context.ProtocolMessage.Wreply = replyUrl;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(homeRealm))
|
||||
{
|
||||
context.ProtocolMessage.Whr = homeRealm;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(authType))
|
||||
{
|
||||
context.ProtocolMessage.Wa = authType;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private sealed class CustomSamlSecurityTokenHandler : SamlSecurityTokenHandler
|
||||
{
|
||||
public override async Task<TokenValidationResult> ValidateTokenAsync(
|
||||
string token,
|
||||
TokenValidationParameters validationParameters)
|
||||
{
|
||||
if (validationParameters.ConfigurationManager is not null)
|
||||
{
|
||||
var federationConfig = await validationParameters.ConfigurationManager
|
||||
.GetBaseConfigurationAsync(CancellationToken.None)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var dynamicIssuers = new[] { federationConfig.Issuer };
|
||||
validationParameters.ValidIssuers = validationParameters.ValidIssuers is null
|
||||
? dynamicIssuers
|
||||
: validationParameters.ValidIssuers.Concat(dynamicIssuers);
|
||||
|
||||
validationParameters.IssuerSigningKeys = validationParameters.IssuerSigningKeys is null
|
||||
? federationConfig.SigningKeys
|
||||
: validationParameters.IssuerSigningKeys.Concat(federationConfig.SigningKeys);
|
||||
}
|
||||
|
||||
return await base.ValidateTokenAsync(token, validationParameters).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using maintenance.Authentication.Abstractions;
|
||||
using maintenance.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
|
||||
namespace maintenance.Authentication.Providers.Oidc;
|
||||
|
||||
public sealed class OidcAuthProvider : IAuthProvider
|
||||
{
|
||||
public const string Scheme = "oidc";
|
||||
|
||||
public string Mode => AuthModes.Oidc;
|
||||
|
||||
public AuthenticationBuilder Configure(
|
||||
AuthenticationBuilder builder,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
"OIDC provider is not implemented yet. Set AUTH_MODE=WSFED for current deployment.");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user