CAS Auth Rv1
This commit is contained in:
@@ -25,5 +25,16 @@
|
||||
public const string OidcRoleClaimType = "OIDC_ROLE_CLAIM_TYPE";
|
||||
public const string OidcNameClaimType = "OIDC_NAME_CLAIM_TYPE";
|
||||
public const string OidcValidIssuers = "OIDC_VALID_ISSUERS";
|
||||
|
||||
public const string CasServerUrl = "CAS_SERVER_URL";
|
||||
public const string CasLoginPath = "CAS_LOGIN_PATH";
|
||||
public const string CasServiceValidatePath = "CAS_SERVICE_VALIDATE_PATH";
|
||||
public const string CasProxyPath = "CAS_PROXY_PATH";
|
||||
public const string CasCallbackPath = "CAS_CALLBACK_PATH";
|
||||
public const string CasProxyCallbackPath = "CAS_PROXY_CALLBACK_PATH";
|
||||
public const string CasProxyCallbackUrl = "CAS_PROXY_CALLBACK_URL";
|
||||
public const string CasNameClaimType = "CAS_NAME_CLAIM_TYPE";
|
||||
public const string CasRoleClaimType = "CAS_ROLE_CLAIM_TYPE";
|
||||
public const string CasRoleAttributeNames = "CAS_ROLE_ATTRIBUTE_NAMES";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
{
|
||||
public class AuthModes
|
||||
{
|
||||
public const string Cas = "CAS";
|
||||
public const string WsFed = "WSFED";
|
||||
public const string Oidc = "OIDC";
|
||||
}
|
||||
|
||||
+14
-4
@@ -9,6 +9,7 @@ using MaxInventory.Authentication.Abstractions;
|
||||
using MaxInventory.Authentication.Configuration;
|
||||
using MaxInventory.Authentication.Core;
|
||||
using MaxInventory.Authentication.Providers.Oidc;
|
||||
using MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
|
||||
namespace MaxInventory.Authentication.Extensions
|
||||
@@ -24,14 +25,22 @@ namespace MaxInventory.Authentication.Extensions
|
||||
services.TryAddSingleton<IAdminGroupSource, ConfiguredAdminGroupSource>();
|
||||
services.TryAddScoped<IPrincipalAccessEvaluator, PrincipalAccessEvaluator>();
|
||||
services.AddScoped<IClaimsTransformation, AdminRoleClaimsTransformation>();
|
||||
services.AddHttpClient();
|
||||
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, AdfsWsFedAuthProvider>());
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, OidcAuthProvider>());
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IAuthProvider, CasAuthProvider>());
|
||||
services.TryAddSingleton<ICasProxyGrantingTicketStore, CasProxyGrantingTicketStore>();
|
||||
services.TryAddSingleton<ICasProxyTicketService, CasProxyTicketService>();
|
||||
|
||||
var authMode = configuration[AuthEnvironment.AuthMode] ?? AuthModes.Oidc;
|
||||
var challengeScheme = authMode.Equals(AuthModes.Oidc, StringComparison.OrdinalIgnoreCase)
|
||||
? OidcAuthProvider.Scheme
|
||||
: AdfsWsFedAuthProvider.Scheme;
|
||||
var challengeScheme = authMode.ToUpperInvariant() switch
|
||||
{
|
||||
AuthModes.Oidc => OidcAuthProvider.Scheme,
|
||||
AuthModes.WsFed => AdfsWsFedAuthProvider.Scheme,
|
||||
AuthModes.Cas => CasAuthProvider.Scheme,
|
||||
_ => throw new InvalidOperationException($"Unsupported AUTH_MODE: {authMode}")
|
||||
};
|
||||
|
||||
var authBuilder = services.AddAuthentication(options =>
|
||||
{
|
||||
@@ -49,7 +58,8 @@ namespace MaxInventory.Authentication.Extensions
|
||||
var providers = new IAuthProvider[]
|
||||
{
|
||||
new OidcAuthProvider(),
|
||||
new AdfsWsFedAuthProvider()
|
||||
new AdfsWsFedAuthProvider(),
|
||||
new CasAuthProvider()
|
||||
};
|
||||
|
||||
var provider = providers.FirstOrDefault(p =>
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using MaxInventory.Authentication.Abstractions;
|
||||
using MaxInventory.Authentication.Configuration;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public sealed class CasAuthProvider : IAuthProvider
|
||||
{
|
||||
public const string Scheme = "cas";
|
||||
|
||||
public string Mode => AuthModes.Cas;
|
||||
|
||||
public AuthenticationBuilder Configure(
|
||||
AuthenticationBuilder builder,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
var serverUrl = configuration[AuthEnvironment.CasServerUrl];
|
||||
if (string.IsNullOrWhiteSpace(serverUrl))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Missing required configuration: {AuthEnvironment.CasServerUrl}");
|
||||
}
|
||||
|
||||
return builder.AddScheme<CasAuthenticationOptions, CasAuthenticationHandler>(
|
||||
Scheme,
|
||||
options =>
|
||||
{
|
||||
options.ServerUrl = serverUrl;
|
||||
options.LoginPath = configuration[AuthEnvironment.CasLoginPath] ?? "/login";
|
||||
options.ServiceValidatePath = configuration[AuthEnvironment.CasServiceValidatePath] ?? "/p3/serviceValidate";
|
||||
options.ProxyPath = configuration[AuthEnvironment.CasProxyPath] ?? "/proxy";
|
||||
options.CallbackPath = configuration[AuthEnvironment.CasCallbackPath] ?? "/signin-cas";
|
||||
options.ProxyCallbackPath = configuration[AuthEnvironment.CasProxyCallbackPath] ?? "/signin-cas-pgt";
|
||||
options.ProxyCallbackUrl = configuration[AuthEnvironment.CasProxyCallbackUrl];
|
||||
options.NameClaimType = configuration[AuthEnvironment.CasNameClaimType]
|
||||
?? "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
|
||||
options.RoleClaimType = configuration[AuthEnvironment.CasRoleClaimType]
|
||||
?? "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
|
||||
options.RoleAttributeNames = (configuration[AuthEnvironment.CasRoleAttributeNames] ?? "memberOf;groups;roles")
|
||||
.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public sealed class CasAuthenticationHandler :
|
||||
AuthenticationHandler<CasAuthenticationOptions>,
|
||||
IAuthenticationRequestHandler
|
||||
{
|
||||
private static readonly XNamespace CasNamespace = "http://www.yale.edu/tp/cas";
|
||||
|
||||
private readonly IHttpClientFactory httpClientFactory;
|
||||
private readonly ICasProxyGrantingTicketStore proxyGrantingTicketStore;
|
||||
|
||||
public CasAuthenticationHandler(
|
||||
IOptionsMonitor<CasAuthenticationOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ICasProxyGrantingTicketStore proxyGrantingTicketStore)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
this.httpClientFactory = httpClientFactory;
|
||||
this.proxyGrantingTicketStore = proxyGrantingTicketStore;
|
||||
}
|
||||
|
||||
public async Task<bool> HandleRequestAsync()
|
||||
{
|
||||
if (Options.ProxyCallbackPath.HasValue && Request.Path.Equals(Options.ProxyCallbackPath))
|
||||
{
|
||||
StoreProxyGrantingTicket();
|
||||
Response.StatusCode = StatusCodes.Status200OK;
|
||||
await Response.WriteAsync("OK").ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!Request.Path.Equals(Options.CallbackPath))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var ticket = Request.Query["ticket"].FirstOrDefault();
|
||||
if (string.IsNullOrWhiteSpace(ticket))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var returnUrl = Request.Query["returnUrl"].FirstOrDefault();
|
||||
var serviceUrl = BuildServiceUrl(returnUrl);
|
||||
var principal = await ValidateTicketAsync(ticket, serviceUrl, Context.RequestAborted).ConfigureAwait(false);
|
||||
|
||||
await Context.SignInAsync(
|
||||
CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
principal,
|
||||
new AuthenticationProperties
|
||||
{
|
||||
RedirectUri = GetSafeReturnUrl(returnUrl)
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
Response.Redirect(GetSafeReturnUrl(returnUrl));
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
var returnUrl = properties.RedirectUri;
|
||||
if (string.IsNullOrWhiteSpace(returnUrl))
|
||||
{
|
||||
returnUrl = OriginalPathBase + OriginalPath + Request.QueryString;
|
||||
}
|
||||
|
||||
var serviceUrl = BuildServiceUrl(returnUrl);
|
||||
var redirectUrl = CasUrlBuilder.Build(Options.ServerUrl, Options.LoginPath, new Dictionary<string, string?>
|
||||
{
|
||||
["service"] = serviceUrl
|
||||
});
|
||||
|
||||
Response.Redirect(redirectUrl);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task<ClaimsPrincipal> ValidateTicketAsync(
|
||||
string ticket,
|
||||
string serviceUrl,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var validationParameters = new Dictionary<string, string?>
|
||||
{
|
||||
["service"] = serviceUrl,
|
||||
["ticket"] = ticket,
|
||||
["pgtUrl"] = Options.ProxyCallbackUrl ?? BuildProxyCallbackUrl()
|
||||
};
|
||||
|
||||
var validationUrl = CasUrlBuilder.Build(Options.ServerUrl, Options.ServiceValidatePath, validationParameters);
|
||||
using var response = await httpClientFactory.CreateClient().GetAsync(validationUrl, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
var document = await XDocument.LoadAsync(stream, LoadOptions.None, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var success = document.Descendants(CasNamespace + "authenticationSuccess").FirstOrDefault();
|
||||
if (success is null)
|
||||
{
|
||||
var failure = document.Descendants(CasNamespace + "authenticationFailure").FirstOrDefault()?.Value;
|
||||
throw new InvalidOperationException($"CAS ticket validation failed: {failure ?? "unknown failure"}");
|
||||
}
|
||||
|
||||
var user = success.Element(CasNamespace + "user")?.Value;
|
||||
if (string.IsNullOrWhiteSpace(user))
|
||||
{
|
||||
throw new InvalidOperationException("CAS ticket validation did not return a user.");
|
||||
}
|
||||
|
||||
var identity = new ClaimsIdentity(Scheme.Name, Options.NameClaimType, Options.RoleClaimType);
|
||||
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user));
|
||||
identity.AddClaim(new Claim(Options.NameClaimType, user));
|
||||
|
||||
AddAttributeClaims(identity, success);
|
||||
|
||||
var pgtIou = success.Element(CasNamespace + "proxyGrantingTicket")?.Value;
|
||||
if (!string.IsNullOrWhiteSpace(pgtIou))
|
||||
{
|
||||
identity.AddClaim(new Claim(CasClaims.ProxyGrantingTicketIou, pgtIou));
|
||||
}
|
||||
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
|
||||
private void AddAttributeClaims(ClaimsIdentity identity, XElement success)
|
||||
{
|
||||
var attributes = success.Element(CasNamespace + "attributes");
|
||||
if (attributes is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var attribute in attributes.Elements())
|
||||
{
|
||||
var name = attribute.Name.LocalName;
|
||||
foreach (var value in GetAttributeValues(attribute))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
identity.AddClaim(new Claim(name, value));
|
||||
|
||||
if (Options.RoleAttributeNames.Contains(name, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
identity.AddClaim(new Claim(Options.RoleClaimType, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerable<string> GetAttributeValues(XElement attribute)
|
||||
{
|
||||
var nestedValues = attribute.Elements().Select(element => element.Value);
|
||||
return nestedValues.Any() ? nestedValues : [attribute.Value];
|
||||
}
|
||||
|
||||
private void StoreProxyGrantingTicket()
|
||||
{
|
||||
var pgtIou = Request.Query["pgtIou"].FirstOrDefault();
|
||||
var pgtId = Request.Query["pgtId"].FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(pgtIou) && !string.IsNullOrWhiteSpace(pgtId))
|
||||
{
|
||||
proxyGrantingTicketStore.Store(pgtIou, pgtId);
|
||||
}
|
||||
}
|
||||
|
||||
private string BuildServiceUrl(string? returnUrl)
|
||||
{
|
||||
var uriBuilder = new UriBuilder(Request.Scheme, Request.Host.Host)
|
||||
{
|
||||
Path = OriginalPathBase.Add(Options.CallbackPath).ToString()
|
||||
};
|
||||
|
||||
if (Request.Host.Port is not null)
|
||||
{
|
||||
uriBuilder.Port = Request.Host.Port.Value;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(returnUrl))
|
||||
{
|
||||
uriBuilder.Query = $"returnUrl={Uri.EscapeDataString(GetSafeReturnUrl(returnUrl))}";
|
||||
}
|
||||
|
||||
return uriBuilder.Uri.ToString();
|
||||
}
|
||||
|
||||
private string BuildProxyCallbackUrl()
|
||||
{
|
||||
var uriBuilder = new UriBuilder(Request.Scheme, Request.Host.Host)
|
||||
{
|
||||
Path = OriginalPathBase.Add(Options.ProxyCallbackPath).ToString()
|
||||
};
|
||||
|
||||
if (Request.Host.Port is not null)
|
||||
{
|
||||
uriBuilder.Port = Request.Host.Port.Value;
|
||||
}
|
||||
|
||||
return uriBuilder.Uri.ToString();
|
||||
}
|
||||
|
||||
private static string GetSafeReturnUrl(string? returnUrl)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(returnUrl)
|
||||
&& returnUrl.StartsWith("/", StringComparison.Ordinal)
|
||||
&& !returnUrl.StartsWith("//", StringComparison.Ordinal)
|
||||
&& Uri.IsWellFormedUriString(returnUrl, UriKind.Relative)
|
||||
? returnUrl
|
||||
: "/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public sealed class CasAuthenticationOptions : AuthenticationSchemeOptions
|
||||
{
|
||||
public string ServerUrl { get; set; } = string.Empty;
|
||||
|
||||
public string LoginPath { get; set; } = "/login";
|
||||
|
||||
public string ServiceValidatePath { get; set; } = "/p3/serviceValidate";
|
||||
|
||||
public string ProxyPath { get; set; } = "/proxy";
|
||||
|
||||
public PathString CallbackPath { get; set; } = "/signin-cas";
|
||||
|
||||
public PathString ProxyCallbackPath { get; set; } = "/signin-cas-pgt";
|
||||
|
||||
public string? ProxyCallbackUrl { get; set; }
|
||||
|
||||
public string NameClaimType { get; set; } = string.Empty;
|
||||
|
||||
public string RoleClaimType { get; set; } = string.Empty;
|
||||
|
||||
public string[] RoleAttributeNames { get; set; } = [];
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
internal static class CasClaims
|
||||
{
|
||||
public const string ProxyGrantingTicketIou = "cas:pgtIou";
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public sealed class CasProxyGrantingTicketStore : ICasProxyGrantingTicketStore
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, string> tickets = new(StringComparer.Ordinal);
|
||||
|
||||
public void Store(string proxyGrantingTicketIou, string proxyGrantingTicket)
|
||||
{
|
||||
tickets[proxyGrantingTicketIou] = proxyGrantingTicket;
|
||||
}
|
||||
|
||||
public bool TryGet(string proxyGrantingTicketIou, out string proxyGrantingTicket)
|
||||
{
|
||||
return tickets.TryGetValue(proxyGrantingTicketIou, out proxyGrantingTicket!);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Security.Claims;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public sealed class CasProxyTicketService : ICasProxyTicketService
|
||||
{
|
||||
private static readonly XNamespace CasNamespace = "http://www.yale.edu/tp/cas";
|
||||
|
||||
private readonly IHttpClientFactory httpClientFactory;
|
||||
private readonly ICasProxyGrantingTicketStore ticketStore;
|
||||
private readonly IOptionsMonitor<CasAuthenticationOptions> options;
|
||||
|
||||
public CasProxyTicketService(
|
||||
IHttpClientFactory httpClientFactory,
|
||||
ICasProxyGrantingTicketStore ticketStore,
|
||||
IOptionsMonitor<CasAuthenticationOptions> options)
|
||||
{
|
||||
this.httpClientFactory = httpClientFactory;
|
||||
this.ticketStore = ticketStore;
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
public async Task<string?> GetProxyTicketAsync(
|
||||
ClaimsPrincipal principal,
|
||||
string targetService,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var pgtIou = principal.FindFirstValue(CasClaims.ProxyGrantingTicketIou);
|
||||
if (string.IsNullOrWhiteSpace(pgtIou) || !ticketStore.TryGet(pgtIou, out var pgt))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var casOptions = options.Get(CasAuthProvider.Scheme);
|
||||
var proxyUrl = CasUrlBuilder.Build(casOptions.ServerUrl, casOptions.ProxyPath, new Dictionary<string, string?>
|
||||
{
|
||||
["pgt"] = pgt,
|
||||
["targetService"] = targetService
|
||||
});
|
||||
|
||||
using var response = await httpClientFactory.CreateClient().GetAsync(proxyUrl, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
var document = await XDocument.LoadAsync(stream, LoadOptions.None, cancellationToken).ConfigureAwait(false);
|
||||
return document.Descendants(CasNamespace + "proxyTicket").FirstOrDefault()?.Value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
internal static class CasUrlBuilder
|
||||
{
|
||||
public static string Build(string serverUrl, string path, IReadOnlyDictionary<string, string?> query)
|
||||
{
|
||||
var uriBuilder = new UriBuilder(new Uri(new Uri(EnsureTrailingSlash(serverUrl)), path.TrimStart('/')));
|
||||
var values = query
|
||||
.Where(kvp => !string.IsNullOrWhiteSpace(kvp.Value))
|
||||
.Select(kvp => $"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value!)}");
|
||||
|
||||
uriBuilder.Query = string.Join("&", values);
|
||||
return uriBuilder.Uri.ToString();
|
||||
}
|
||||
|
||||
private static string EnsureTrailingSlash(string value)
|
||||
{
|
||||
return value.EndsWith("/", StringComparison.Ordinal) ? value : $"{value}/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public interface ICasProxyGrantingTicketStore
|
||||
{
|
||||
void Store(string proxyGrantingTicketIou, string proxyGrantingTicket);
|
||||
|
||||
bool TryGet(string proxyGrantingTicketIou, out string proxyGrantingTicket);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace MaxInventory.Authentication.Providers.Cas;
|
||||
|
||||
public interface ICasProxyTicketService
|
||||
{
|
||||
Task<string?> GetProxyTicketAsync(
|
||||
ClaimsPrincipal principal,
|
||||
string targetService,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
Reference in New Issue
Block a user