fix(dashboard): enforce auth lifetimes on live hub connections and circuits (DSH-006)
Hub tokens and cookies bounded only the handshake: an open hub socket kept its connect-time roles and tag grants indefinitely, and a Blazor circuit never revisited its sign-in. The hub-token ticket now carries the token expiry and the hubs are mapped with CloseOnAuthenticationExpiration. Circuits use DashboardRevalidatingAuthenticationStateProvider, which signs a circuit out past the cookie's 8-hour idle lifetime or when a role it holds is no longer granted by GroupToRole. LDAP membership changes and sign-out in another tab are still only picked up at the age limit or on reconnect (documented).
This commit is contained in:
@@ -45,6 +45,13 @@ public static class DashboardAuthenticationDefaults
|
||||
/// </summary>
|
||||
public const string AlarmsPolicy = "MxGateway.Dashboard.Alarms";
|
||||
|
||||
/// <summary>
|
||||
/// Sliding idle lifetime of the dashboard login cookie. Also the longest a Blazor circuit keeps
|
||||
/// its sign-in: the circuit issues no HTTP requests, so it cannot renew the cookie, and
|
||||
/// <see cref="DashboardRevalidatingAuthenticationStateProvider"/> signs it out at this age.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan CookieIdleTimeout = TimeSpan.FromHours(8);
|
||||
|
||||
public const string LdapGroupClaimType = "mxgateway:ldap_group";
|
||||
public const string KeyPrefixClaimType = "mxgateway:key_prefix";
|
||||
|
||||
|
||||
+13
-3
@@ -109,9 +109,14 @@ public static class DashboardEndpointRouteBuilderExtensions
|
||||
// events use HubClientsPolicy; AlarmsHub uses AlarmsPolicy, which additionally requires a
|
||||
// real authenticated dashboard role — see AlarmsHub for why the alarm feed is
|
||||
// gated harder than the session-scoped ones.
|
||||
endpoints.MapHub<DashboardSnapshotHub>("/hubs/snapshot");
|
||||
endpoints.MapHub<AlarmsHub>("/hubs/alarms");
|
||||
endpoints.MapHub<EventsHub>("/hubs/events");
|
||||
// CloseOnAuthenticationExpiration (DSH-006): a hub connection authenticates once, at the
|
||||
// handshake, and keeps that principal for as long as the socket stays up. Closing it when
|
||||
// the ticket expires — the hub token's 5 minutes, or the cookie ticket's expiry — makes a
|
||||
// long-lived connection re-authenticate, so a revoked role or tag grant cannot outlive it.
|
||||
// Remote clients already re-fetch /hubs/token on every (re)connect.
|
||||
endpoints.MapHub<DashboardSnapshotHub>("/hubs/snapshot", CloseOnAuthenticationExpiration);
|
||||
endpoints.MapHub<AlarmsHub>("/hubs/alarms", CloseOnAuthenticationExpiration);
|
||||
endpoints.MapHub<EventsHub>("/hubs/events", CloseOnAuthenticationExpiration);
|
||||
|
||||
// Bearer-token mint endpoint. The cookie-authenticated browser hits
|
||||
// this from JS before opening a hub connection; the hub then accepts
|
||||
@@ -140,6 +145,11 @@ public static class DashboardEndpointRouteBuilderExtensions
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
// Applied to every dashboard hub; internal so a test can assert the options each hub gets.
|
||||
internal static void CloseOnAuthenticationExpiration(
|
||||
Microsoft.AspNetCore.Http.Connections.HttpConnectionDispatcherOptions options) =>
|
||||
options.CloseOnAuthenticationExpiration = true;
|
||||
|
||||
private static async Task<IResult> PostLoginAsync(
|
||||
HttpContext httpContext,
|
||||
IAntiforgery antiforgery,
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Re-checks a Blazor circuit's sign-in on a timer and signs the circuit out when it no longer
|
||||
/// holds (DSH-006).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A circuit captures its principal once, at circuit start, and an open tab issues no further HTTP
|
||||
/// requests, so neither cookie expiry nor a configuration change ever reached it: an Administrator
|
||||
/// tab left open could still close sessions, kill workers and manage API keys hours later. Every
|
||||
/// <see cref="RevalidationInterval"/> this provider re-evaluates two things it can know without the
|
||||
/// user's password:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item><description>
|
||||
/// <b>Age.</b> A circuit older than the cookie's idle lifetime
|
||||
/// (<see cref="DashboardAuthenticationDefaults.CookieIdleTimeout"/>) is signed out; the circuit
|
||||
/// could not have renewed the cookie, so the sign-in it holds has lapsed.
|
||||
/// </description></item>
|
||||
/// <item><description>
|
||||
/// <b>Roles.</b> The principal's LDAP group claims are re-mapped through the current
|
||||
/// <c>MxGateway:Dashboard:GroupToRole</c>; if a role the principal carries is no longer granted, the
|
||||
/// circuit is signed out. This is the same re-resolution the session ACL applies to tag grants.
|
||||
/// </description></item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// When either check fails the circuit's state becomes anonymous: pages under
|
||||
/// <c>AuthorizeRouteView</c> re-render as not authorized, and admin actions — which read the
|
||||
/// provider at action time — are refused. A change to the user's LDAP group membership, and a
|
||||
/// sign-out in another tab, are not observable here (the gateway keeps no server-side session and
|
||||
/// cannot re-bind without the password); they take effect when the circuit reaches the age limit or
|
||||
/// reconnects. The <c>Dashboard:DisableLogin</c> dev bypass and unauthenticated principals are
|
||||
/// never signed out.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider
|
||||
{
|
||||
private readonly IOptionsMonitor<GatewayOptions> _options;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly DateTimeOffset _circuitStartedAt;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="DashboardRevalidatingAuthenticationStateProvider"/> class.</summary>
|
||||
/// <param name="loggerFactory">Logger factory for the revalidation loop.</param>
|
||||
/// <param name="options">Gateway options, read fresh on every revalidation.</param>
|
||||
/// <param name="timeProvider">Clock; the system clock when not registered.</param>
|
||||
public DashboardRevalidatingAuthenticationStateProvider(
|
||||
ILoggerFactory loggerFactory,
|
||||
IOptionsMonitor<GatewayOptions> options,
|
||||
TimeProvider? timeProvider = null)
|
||||
: base(loggerFactory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_options = options;
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
_circuitStartedAt = _timeProvider.GetUtcNow();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>Decides whether the circuit's principal is still signed in. Internal for tests.</summary>
|
||||
/// <param name="user">The circuit's current principal.</param>
|
||||
/// <returns><see langword="true"/> to keep the sign-in; <see langword="false"/> to sign out.</returns>
|
||||
internal bool IsStillValid(ClaimsPrincipal user)
|
||||
{
|
||||
if (user.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
GatewayOptions options = _options.CurrentValue;
|
||||
if (options.Dashboard.DisableLogin)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_timeProvider.GetUtcNow() - _circuitStartedAt >= DashboardAuthenticationDefaults.CookieIdleTimeout)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string[] groups = [.. user.FindAll(DashboardAuthenticationDefaults.LdapGroupClaimType).Select(claim => claim.Value)];
|
||||
if (groups.Length == 0)
|
||||
{
|
||||
// Nothing to re-resolve from (a principal minted without LDAP groups); the age check
|
||||
// above is the bound.
|
||||
return true;
|
||||
}
|
||||
|
||||
IReadOnlyList<string> grantedRoles = DashboardGroupRoleMapping.MapGroupsToRoles(
|
||||
groups,
|
||||
options.Dashboard.GroupToRole);
|
||||
foreach (Claim role in user.FindAll(ClaimTypes.Role))
|
||||
{
|
||||
if (!grantedRoles.Contains(role.Value, StringComparer.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<bool> ValidateAuthenticationStateAsync(
|
||||
AuthenticationState authenticationState,
|
||||
CancellationToken cancellationToken) =>
|
||||
Task.FromResult(IsStillValid(authenticationState.User));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server.Circuits;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
@@ -114,6 +115,10 @@ public static class DashboardServiceCollectionExtensions
|
||||
services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents(circuit =>
|
||||
circuit.DisconnectedCircuitRetentionPeriod = DisconnectedCircuitRetention);
|
||||
// Registered after AddInteractiveServerComponents so it replaces the default
|
||||
// ServerAuthenticationStateProvider: a circuit's sign-in is otherwise captured once at
|
||||
// circuit start and never revisited (DSH-006).
|
||||
services.AddScoped<AuthenticationStateProvider, DashboardRevalidatingAuthenticationStateProvider>();
|
||||
services.AddSignalR();
|
||||
|
||||
// DEV/TEST ONLY. Read directly from configuration here because authentication scheme
|
||||
@@ -154,7 +159,7 @@ public static class DashboardServiceCollectionExtensions
|
||||
// ExpireTimeSpan) via the shared ZbCookieDefaults.Apply. requireHttps is set to
|
||||
// its default (true / Always) here and overridden per-environment by the
|
||||
// PostConfigure below; the 8-hour idle timeout is preserved (not the 30-min default).
|
||||
ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: TimeSpan.FromHours(8));
|
||||
ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: DashboardAuthenticationDefaults.CookieIdleTimeout);
|
||||
// Cookie name, path, and redirect paths are MxGateway-specific — set after Apply
|
||||
// so they are never overwritten by the shared helper (Apply intentionally skips name).
|
||||
// This is the canonical default; it is overridden per-environment from
|
||||
|
||||
@@ -48,14 +48,19 @@ public sealed class HubTokenAuthenticationHandler : AuthenticationHandler<Authen
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token);
|
||||
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token, out DateTimeOffset expiresUtc);
|
||||
if (principal is null)
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.Fail("Invalid or expired hub token."));
|
||||
}
|
||||
|
||||
// The ticket carries the token's expiry so the hubs, mapped with
|
||||
// CloseOnAuthenticationExpiration, close a token-authenticated connection when its token
|
||||
// lapses (DSH-006). Without it the 5-minute lifetime bounded only the handshake: an open
|
||||
// socket kept the roles and tag grants it connected with for as long as it stayed up.
|
||||
AuthenticationProperties properties = new() { ExpiresUtc = expiresUtc };
|
||||
return Task.FromResult(AuthenticateResult.Success(
|
||||
new AuthenticationTicket(principal, Scheme.Name)));
|
||||
new AuthenticationTicket(principal, properties, Scheme.Name)));
|
||||
}
|
||||
|
||||
private string? ExtractToken()
|
||||
|
||||
@@ -100,8 +100,19 @@ public sealed class HubTokenService
|
||||
/// <summary>Validates a token and returns the equivalent claims principal; null when invalid or expired.</summary>
|
||||
/// <param name="token">The token string to validate.</param>
|
||||
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/> when the token is missing, invalid, or expired.</returns>
|
||||
public ClaimsPrincipal? Validate(string? token)
|
||||
public ClaimsPrincipal? Validate(string? token) => Validate(token, out _);
|
||||
|
||||
/// <summary>
|
||||
/// Validates a token and returns the equivalent claims principal and the token's expiry; null
|
||||
/// when invalid or expired. The expiry is stamped on the hub authentication ticket so SignalR's
|
||||
/// <c>CloseOnAuthenticationExpiration</c> ends the connection when the token lapses (DSH-006).
|
||||
/// </summary>
|
||||
/// <param name="token">The token string to validate.</param>
|
||||
/// <param name="expiresUtc">The token's expiry when valid; otherwise <see langword="default"/>.</param>
|
||||
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/>.</returns>
|
||||
public ClaimsPrincipal? Validate(string? token, out DateTimeOffset expiresUtc)
|
||||
{
|
||||
expiresUtc = default;
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return null;
|
||||
@@ -109,7 +120,8 @@ public sealed class HubTokenService
|
||||
|
||||
try
|
||||
{
|
||||
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(_protector.Unprotect(token));
|
||||
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(
|
||||
_protector.Unprotect(token, out DateTimeOffset expiration));
|
||||
if (payload is null)
|
||||
{
|
||||
return null;
|
||||
@@ -149,6 +161,7 @@ public sealed class HubTokenService
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
ClaimTypes.Name,
|
||||
ClaimTypes.Role);
|
||||
expiresUtc = expiration;
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
catch (Exception ex) when (ex is CryptographicException or JsonException)
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Connections;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// DSH-006: authentication lifetimes are enforced on live dashboard connections, not only at the
|
||||
/// handshake — hub connections close when their ticket expires, and Blazor circuits are signed out
|
||||
/// when their sign-in lapses or a role grant is withdrawn.
|
||||
/// </summary>
|
||||
public sealed class DashboardAuthLifetimeTests
|
||||
{
|
||||
private const string AdminGroup = "GwAdmin";
|
||||
private const string ViewerGroup = "GwViewer";
|
||||
|
||||
/// <summary>
|
||||
/// The hub-token ticket carries the token's expiry, which is what SignalR's
|
||||
/// CloseOnAuthenticationExpiration closes the connection on.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task HubTokenTicket_CarriesTheTokenExpiry()
|
||||
{
|
||||
HubTokenService tokens = new(
|
||||
new EphemeralDataProtectionProvider(),
|
||||
Options.Create(new GatewayOptions()));
|
||||
string token = tokens.Issue(Principal("alice", DashboardRoles.Viewer), TimeSpan.FromMinutes(5));
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Request.Headers.Authorization = $"Bearer {token}";
|
||||
|
||||
HubTokenAuthenticationHandler handler = new(
|
||||
new StaticOptionsMonitor<AuthenticationSchemeOptions>(new AuthenticationSchemeOptions()),
|
||||
NullLoggerFactory.Instance,
|
||||
UrlEncoder.Default,
|
||||
tokens);
|
||||
await handler.InitializeAsync(
|
||||
new AuthenticationScheme(
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
displayName: null,
|
||||
typeof(HubTokenAuthenticationHandler)),
|
||||
httpContext);
|
||||
|
||||
AuthenticateResult result = await handler.AuthenticateAsync();
|
||||
|
||||
Assert.True(result.Succeeded);
|
||||
DateTimeOffset? expires = result.Properties?.ExpiresUtc;
|
||||
Assert.NotNull(expires);
|
||||
Assert.InRange(
|
||||
expires.Value,
|
||||
DateTimeOffset.UtcNow.AddMinutes(4),
|
||||
DateTimeOffset.UtcNow.AddMinutes(6));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every dashboard hub closes a connection whose authentication has expired. The dispatcher
|
||||
/// options ride on each hub's negotiate endpoint.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task EveryHub_ClosesOnAuthenticationExpiration()
|
||||
{
|
||||
await using WebApplication app = TestGatewayHost.Build([]);
|
||||
List<RouteEndpoint> hubEndpoints = ((IEndpointRouteBuilder)app).DataSources
|
||||
.SelectMany(source => source.Endpoints)
|
||||
.OfType<RouteEndpoint>()
|
||||
.Where(endpoint => endpoint.RoutePattern.RawText
|
||||
is "/hubs/snapshot/negotiate" or "/hubs/alarms/negotiate" or "/hubs/events/negotiate")
|
||||
.ToList();
|
||||
|
||||
Assert.Equal(3, hubEndpoints.Count);
|
||||
Assert.All(
|
||||
hubEndpoints,
|
||||
endpoint => Assert.True(endpoint.Metadata.GetMetadata<HttpConnectionDispatcherOptions>()?.CloseOnAuthenticationExpiration));
|
||||
}
|
||||
|
||||
/// <summary>Circuits get the revalidating provider, not the capture-once default.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Circuits_UseTheRevalidatingAuthenticationStateProvider()
|
||||
{
|
||||
await using WebApplication app = TestGatewayHost.Build([]);
|
||||
await using AsyncServiceScope scope = app.Services.CreateAsyncScope();
|
||||
|
||||
Assert.IsType<DashboardRevalidatingAuthenticationStateProvider>(
|
||||
scope.ServiceProvider.GetRequiredService<AuthenticationStateProvider>());
|
||||
}
|
||||
|
||||
/// <summary>An Administrator whose admin group is withdrawn from GroupToRole is signed out.</summary>
|
||||
[Fact]
|
||||
public void Revalidation_WhenAdminGrantWithdrawn_SignsOut()
|
||||
{
|
||||
GatewayOptions options = OptionsWithRoles(includeAdmin: true);
|
||||
StaticOptionsMonitor<GatewayOptions> monitor = new(options);
|
||||
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
|
||||
ClaimsPrincipal admin = Principal("alice", DashboardRoles.Admin, groups: [AdminGroup]);
|
||||
|
||||
Assert.True(provider.IsStillValid(admin));
|
||||
|
||||
monitor.CurrentValue = OptionsWithRoles(includeAdmin: false);
|
||||
|
||||
Assert.False(provider.IsStillValid(admin));
|
||||
}
|
||||
|
||||
/// <summary>A circuit older than the cookie's idle lifetime is signed out.</summary>
|
||||
[Fact]
|
||||
public void Revalidation_PastCookieIdleTimeout_SignsOut()
|
||||
{
|
||||
StaticOptionsMonitor<GatewayOptions> monitor = new(OptionsWithRoles(includeAdmin: true));
|
||||
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
|
||||
ClaimsPrincipal viewer = Principal("bob", DashboardRoles.Viewer, groups: [ViewerGroup]);
|
||||
|
||||
clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout - TimeSpan.FromMinutes(1));
|
||||
Assert.True(provider.IsStillValid(viewer));
|
||||
|
||||
clock.Advance(TimeSpan.FromMinutes(1));
|
||||
Assert.False(provider.IsStillValid(viewer));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Principals with nothing to revoke stay as they are: anonymous localhost, and the
|
||||
/// DisableLogin dev bypass however old the circuit.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Revalidation_AnonymousAndDisableLogin_AreNeverSignedOut()
|
||||
{
|
||||
StaticOptionsMonitor<GatewayOptions> monitor = new(new GatewayOptions
|
||||
{
|
||||
Dashboard = new DashboardOptions { DisableLogin = true },
|
||||
});
|
||||
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
|
||||
|
||||
clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout * 2);
|
||||
|
||||
Assert.True(provider.IsStillValid(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
Assert.True(provider.IsStillValid(Principal("multi-role", DashboardRoles.Admin)));
|
||||
}
|
||||
|
||||
private static GatewayOptions OptionsWithRoles(bool includeAdmin)
|
||||
{
|
||||
Dictionary<string, string> groupToRole = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[ViewerGroup] = DashboardRoles.Viewer,
|
||||
};
|
||||
if (includeAdmin)
|
||||
{
|
||||
groupToRole[AdminGroup] = DashboardRoles.Admin;
|
||||
}
|
||||
|
||||
return new GatewayOptions { Dashboard = new DashboardOptions { GroupToRole = groupToRole } };
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal Principal(string name, string role, string[]? groups = null)
|
||||
{
|
||||
List<Claim> claims =
|
||||
[
|
||||
new(ClaimTypes.Name, name),
|
||||
new(ClaimTypes.NameIdentifier, name),
|
||||
new(ClaimTypes.Role, role),
|
||||
];
|
||||
claims.AddRange((groups ?? []).Select(group => new Claim(DashboardAuthenticationDefaults.LdapGroupClaimType, group)));
|
||||
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Test", ClaimTypes.Name, ClaimTypes.Role));
|
||||
}
|
||||
|
||||
private sealed class StaticOptionsMonitor<T>(T value) : IOptionsMonitor<T>
|
||||
{
|
||||
public T CurrentValue { get; set; } = value;
|
||||
|
||||
public T Get(string? name) => CurrentValue;
|
||||
|
||||
public IDisposable? OnChange(Action<T, string?> listener) => null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user