/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace Opc.Ua.Identity
{
///
/// A JSON Web Key (JWK) — the subset of RFC 7517 that the JWT
/// authenticator needs to verify a signature.
///
///
///
/// Used by implementations to
/// publish their verification keys without coupling to a specific
/// JWT library or to the
/// System.IdentityModel.Tokens.Jwt AOT-unfriendly stack.
///
///
/// The implementation only supports asymmetric keys (RSA, ECDSA);
/// HS256 (HMAC) is intentionally not supported because it would
/// require sharing a symmetric secret with each verifier, which is
/// incompatible with the multi-party OPC UA authorization model.
///
///
public sealed class IssuerVerificationKey : IDisposable
{
private readonly AsymmetricAlgorithm m_key;
private bool m_disposed;
///
/// Wraps an asymmetric verification key. Ownership transfers to
/// the : disposing the key
/// disposes the underlying algorithm.
///
///
/// JWK kid used to match the JWT header. May be
/// when the issuer does not include a
/// kid in the JOSE header — in that case the resolver
/// returns its single configured key.
///
///
/// Either an or an public
/// key.
///
///
/// The JWS algorithm name from RFC 7518 §3.1 (e.g. RS256,
/// RS384, RS512, ES256, ES384,
/// ES512, PS256).
///
public IssuerVerificationKey(string? keyId, AsymmetricAlgorithm key, string algorithm)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (string.IsNullOrEmpty(algorithm))
{
throw new ArgumentException(
"Algorithm must be supplied.",
nameof(algorithm));
}
if (key is not RSA and not ECDsa)
{
throw new ArgumentException(
"Only RSA and ECDsa keys are supported.",
nameof(key));
}
KeyId = keyId;
m_key = key;
Algorithm = algorithm;
}
/// JWK kid matched against the JWT header.
public string? KeyId { get; }
///
/// JWS algorithm (RFC 7518).
///
public string Algorithm { get; }
///
/// Verifies an RFC 7515 signed JWS over the supplied signing
/// input (the canonical
/// base64url(header) + "." + base64url(payload) bytes).
///
///
/// Uses [] parameters for compatibility with
/// the netstandard2.1 / net472 / net48 surface.
///
///
/// is null.
public bool VerifySignature(byte[] signingInput, byte[] signature)
{
if (m_disposed)
{
throw new ObjectDisposedException(nameof(IssuerVerificationKey));
}
if (signingInput == null)
{
throw new ArgumentNullException(nameof(signingInput));
}
if (signature == null)
{
throw new ArgumentNullException(nameof(signature));
}
HashAlgorithmName hash = HashFromAlgorithm(Algorithm);
return m_key switch
{
RSA rsa => Algorithm.StartsWith("PS", StringComparison.Ordinal)
? rsa.VerifyData(signingInput, signature, hash, RSASignaturePadding.Pss)
: rsa.VerifyData(signingInput, signature, hash, RSASignaturePadding.Pkcs1),
ECDsa ec => ec.VerifyData(signingInput, signature, hash),
_ => false
};
}
///
public void Dispose()
{
if (m_disposed)
{
return;
}
m_disposed = true;
m_key.Dispose();
}
private static HashAlgorithmName HashFromAlgorithm(string alg)
{
return alg switch
{
"RS256" or "PS256" or "ES256" => HashAlgorithmName.SHA256,
"RS384" or "PS384" or "ES384" => HashAlgorithmName.SHA384,
"RS512" or "PS512" or "ES512" => HashAlgorithmName.SHA512,
_ => throw new NotSupportedException(
$"JWS algorithm '{alg}' is not supported.")
};
}
}
///
/// Resolves the verification keys for an Authorization Service so a
/// server-side JwtAuthenticator can verify the signature of
/// an inbound JWT-bearing IssuedIdentityToken.
///
///
///
/// Implementations:
///
///
/// - StaticIssuerKeyResolver — keys baked into config /
/// test fixtures.
/// - JwksIssuerKeyResolver — fetches RFC 7517 JWKS from
/// the issuer's jwks_uri with caching + rotation
/// handling.
/// - OidcDiscoveryIssuerKeyResolver — resolves
/// jwks_uri via .well-known/openid-configuration.
/// - X509CertificateIssuerKeyResolver — uses the
/// configured signing cert of a local Authorization Service.
///
///
/// The interface is async because real implementations may fetch
/// keys over HTTP. Implementations SHOULD cache to keep the
/// hot-path synchronous after the first call.
///
///
public interface IIssuerKeyResolver
{
///
/// The issuer URI this resolver is configured for. Used by a
/// composite resolver to dispatch by JWT iss claim.
///
string IssuerUri { get; }
///
/// Returns candidate verification keys for the supplied
/// (JOSE kid). When
/// is the
/// resolver returns every key it knows of (the caller will try
/// each in turn).
///
///
/// Returned keys are owned by the resolver; callers MUST NOT
/// dispose them. The lifetime is at least the duration of the
/// returned .
///
ValueTask> GetKeysAsync(
string? keyId,
CancellationToken ct = default);
}
}