fix(security): validate the API-key pepper at start, finish JWT bearer, circuit-aware audit actor
- ApiKeyOptionsValidator (ValidateOnStart on any driver/admin node): a blank or placeholder Security:ApiKeys:Pepper fails host start instead of rejecting every key after a green boot (R03:2.3). - JWT is finished and opt-in by key (R03:2.4): with Security:Jwt:SigningKey set, a Bearer scheme (JwtBearerAuthenticationHandler over JwtTokenService.TryValidate / BuildValidationParameters, fail closed) accepts the tokens /auth/token mints; the default scheme is a cookie-or-bearer policy scheme and the fallback policy names it, so /api/* and every RequireAuthorization endpoint take a browser session OR a machine token. JwtOptions are validated at start (JwtOptionsValidator). Without a key, /auth/token is not mapped (404, not the former constructor 500) and no bearer scheme exists. A direct AddJwtBearer needs Microsoft.AspNetCore.Authentication.JwtBearer in Directory.Packages.props (not this lane's file) — the handler is a drop-in to swap. - AuthenticationStateAuditActorAccessor is the registered IAuditActorAccessor: the Blazor circuit's principal first, HttpContext as the fallback (R03:2.5). HttpAuditActorAccessor shares its resolver. - CookieAuthenticationStateProvider (unregistered, fire-and-forget ping loop) is deleted (R03:1.5/2.5). - /auth/login logs the LDAP exception at Warning before answering 503 (R03:2.7). - Admin operations reply with a fixed message + correlation id instead of ex.Message (R03:4.1). Refs #733 Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Primitives;
|
||||
using ZB.MOM.WW.OtOpcUa.Security.Jwt;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Auth;
|
||||
|
||||
/// <summary>The authentication scheme names OtOpcUa registers.</summary>
|
||||
public static class OtOpcUaAuthSchemes
|
||||
{
|
||||
/// <summary>
|
||||
/// The bearer scheme that validates the HS256 tokens <c>/auth/token</c> mints, through
|
||||
/// <see cref="JwtTokenService.BuildValidationParameters"/>. Registered only when
|
||||
/// <see cref="JwtOptions.IsConfigured"/>.
|
||||
/// </summary>
|
||||
public const string Bearer = "Bearer";
|
||||
|
||||
/// <summary>
|
||||
/// The default scheme: a policy scheme that forwards to <see cref="Bearer"/> when the request
|
||||
/// carries an <c>Authorization: Bearer</c> header and to the cookie scheme otherwise, so one
|
||||
/// <c>RequireAuthorization()</c> / policy accepts a browser session AND a machine token.
|
||||
/// </summary>
|
||||
public const string CookieOrBearer = "OtOpcUa.CookieOrBearer";
|
||||
|
||||
/// <summary>Whether the request presents a bearer token (the selector's whole rule).</summary>
|
||||
/// <param name="context">The request.</param>
|
||||
/// <returns><see langword="true"/> when an <c>Authorization: Bearer …</c> header is present.</returns>
|
||||
public static bool HasBearerToken(HttpContext context) =>
|
||||
TryGetBearerToken(context.Request.Headers.Authorization, out _);
|
||||
|
||||
internal static bool TryGetBearerToken(StringValues authorization, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
var header = authorization.ToString();
|
||||
const string prefix = "Bearer ";
|
||||
if (!header.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
token = header[prefix.Length..].Trim();
|
||||
return token.Length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates an <c>Authorization: Bearer</c> token minted by <c>/auth/token</c> (R03:2.4). The JWT
|
||||
/// feature used to be a dead end: tokens were issued and nothing in the product accepted them. This
|
||||
/// handler is the consuming side, built on <see cref="JwtTokenService.TryValidate"/> so the validation
|
||||
/// parameters can never drift from the minting side (<see cref="JwtTokenService.BuildValidationParameters"/>
|
||||
/// sets <c>RoleClaimType</c>/<c>NameClaimType</c> to the minted keys, so <c>[Authorize(Roles)]</c> and
|
||||
/// <c>IsInRole</c> resolve).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Fail closed: no header ⇒ <c>NoResult</c> (the cookie scheme is not consulted by this handler — the
|
||||
/// policy scheme selects one or the other); a malformed, expired, tampered or wrong-issuer token ⇒
|
||||
/// <c>Fail</c>, never a fall-through to the cookie. A direct <c>AddJwtBearer</c> needs the
|
||||
/// <c>Microsoft.AspNetCore.Authentication.JwtBearer</c> package, which the central package list does
|
||||
/// not carry; this handler is ~40 lines over the already-referenced <c>System.IdentityModel.Tokens.Jwt</c>
|
||||
/// and is a drop-in to replace once that package is pinned.
|
||||
/// </remarks>
|
||||
public sealed class JwtBearerAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
||||
{
|
||||
private readonly JwtTokenService _jwt;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="JwtBearerAuthenticationHandler"/> class.</summary>
|
||||
/// <param name="options">The scheme options monitor.</param>
|
||||
/// <param name="logger">The logger factory.</param>
|
||||
/// <param name="encoder">The URL encoder.</param>
|
||||
/// <param name="jwt">The token service whose validation parameters mirror its minting side.</param>
|
||||
public JwtBearerAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
JwtTokenService jwt)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
_jwt = jwt;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!OtOpcUaAuthSchemes.TryGetBearerToken(Request.Headers.Authorization, out var token))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
|
||||
if (!_jwt.TryValidate(token, out var principal) || principal is null)
|
||||
return Task.FromResult(AuthenticateResult.Fail("Invalid bearer token."));
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
|
||||
{
|
||||
Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
Response.Headers.WWWAuthenticate = OtOpcUaAuthSchemes.Bearer;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user