mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-28 22:55:49 +08:00
# Description Introduces a pluggable user-identity provider model covering all OPC UA Part 6 §6.5 mechanisms (Anonymous, UserName, X509, IssuedToken/JWT) on both client and server, with full `Microsoft.Extensions.DependencyInjection` integration, plus the Part 12 §9 `AuthorizationService` two-phase token-request flow **including refresh-token rotation**, the Part 12 §8 KeyCredential Push model, and a clean provider model for OPC 10000-12 §7.2 `ApplicationSelfAdmin`. The work is split across phase-by-phase commits so it can be reviewed independently; nothing here changes wire-level behaviour or forces existing applications to migrate. ### Documentation All under `Docs/`: - `IdentityProviders.md` — full developer guide: three-layer model, recipes, configuration reference, "what gets auto-wired" matrix, JWS algorithm table, identity-augmenters section, **"Implementing your own provider"** how-to subsections for Entra / OIDC / Windows / AspNetCore (sibling files merged in per review feedback). - `DependencyInjection.md` — `Identity` sections with `appsettings.json` examples, identity-extension matrix, `WithAuthorizationService` + `WithKeyCredentialPush` + `AddIdentityAugmenter` extensions documented. - `RoleBasedUserManagement.md` — claim-criteria callout describing `IIdentityClaims` probe surface. - `AuthorizationService.md` — Architecture diagram + `IAccessTokenProvider` conceptual narrative restored from master; modern `StartRequestToken` / `FinishRequestToken` flow leads; refresh-token recipe added. - `KeyCredentialService.md` — Push model + Pull vs Push vs Bridge decision matrix + Hybrid (Push + Pull) section; explicit experimental warning for the bridge. - `GDS.md` — KeyCredential Push, `StartRequestToken`, `GdsApplicationSelfAdminProvider`, **shipped Refresh-token support with rotation policy and audit semantics** all documented. - `MigrationGuide.md` — User Identity Providers section listing `[Obsolete]` markers + mechanical recipes; SelfAdmin migration via `IIdentityAugmenter`; `EnableRefreshTokens` default note. - `README.md` index entries. ## Checklist - [x] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [x] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. - [x] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [x] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [x] I have addressed **all** PR feedback received.
278 lines
11 KiB
C#
278 lines
11 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 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.IO;
|
|
using System.Text;
|
|
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Security.Cryptography.X509Certificates;
|
|
using System.Security.Cryptography;
|
|
#endif
|
|
|
|
namespace Opc.Ua.Security.Certificates
|
|
{
|
|
/// <summary>
|
|
/// Write certificate/crl data in PEM format.
|
|
/// </summary>
|
|
public static
|
|
#if NETFRAMEWORK
|
|
partial
|
|
#endif
|
|
class PEMWriter
|
|
{
|
|
/// <summary>
|
|
/// Returns a byte array containing the CRL in PEM format.
|
|
/// </summary>
|
|
public static byte[] ExportCRLAsPEM(byte[] crl)
|
|
{
|
|
return EncodeAsPEM(crl, "X509 CRL");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the CSR in PEM format.
|
|
/// </summary>
|
|
public static byte[] ExportCSRAsPEM(byte[] csr)
|
|
{
|
|
return EncodeAsPEM(csr, "CERTIFICATE REQUEST");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the cert in PEM format.
|
|
/// </summary>
|
|
public static byte[] ExportCertificateAsPEM(Certificate certificate)
|
|
{
|
|
return EncodeAsPEM(certificate.RawData, "CERTIFICATE");
|
|
}
|
|
|
|
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
|
|
/// <summary>
|
|
/// Returns a byte array containing the public key in PEM format.
|
|
/// </summary>
|
|
/// <exception cref="CryptographicException"></exception>
|
|
public static byte[] ExportPublicKeyAsPEM(Certificate certificate)
|
|
{
|
|
using RSA rsaPublicKey = certificate.GetRSAPublicKey()
|
|
?? throw new CryptographicException("RSA public key not found.");
|
|
byte[] exportedPublicKey = rsaPublicKey.ExportSubjectPublicKeyInfo();
|
|
return EncodeAsPEM(exportedPublicKey, "PUBLIC KEY");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the RSA private key in PEM format.
|
|
/// </summary>
|
|
/// <exception cref="CryptographicException"></exception>
|
|
public static byte[] ExportRSAPrivateKeyAsPEM(Certificate certificate)
|
|
{
|
|
using RSA rsaPrivateKey = certificate.GetRSAPrivateKey()
|
|
?? throw new CryptographicException("RSA private key not found.");
|
|
// write private key as PKCS#1
|
|
byte[] exportedRSAPrivateKey = rsaPrivateKey.ExportRSAPrivateKey();
|
|
return EncodeAsPEM(exportedRSAPrivateKey, "RSA PRIVATE KEY");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the ECDsa private key in PEM format.
|
|
/// </summary>
|
|
/// <exception cref="CryptographicException"></exception>
|
|
public static byte[] ExportECDsaPrivateKeyAsPEM(Certificate certificate)
|
|
{
|
|
using ECDsa ecdsaPrivateKey = certificate.GetECDsaPrivateKey()
|
|
?? throw new CryptographicException("ECDsa private key not found.");
|
|
// write private key as PKCS#1
|
|
byte[] exportedECPrivateKey = ecdsaPrivateKey.ExportECPrivateKey();
|
|
return EncodeAsPEM(exportedECPrivateKey, "EC PRIVATE KEY");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the private key in PEM format.
|
|
/// </summary>
|
|
/// <exception cref="CryptographicException"></exception>
|
|
public static byte[] ExportPrivateKeyAsPEM(
|
|
Certificate certificate,
|
|
ReadOnlySpan<char> password = default)
|
|
{
|
|
byte[]? exportedPkcs8PrivateKey = null;
|
|
using (RSA? rsaPrivateKey = certificate.GetRSAPrivateKey())
|
|
{
|
|
if (rsaPrivateKey != null)
|
|
{
|
|
// write private key as PKCS#8
|
|
exportedPkcs8PrivateKey = password.IsEmpty || password.IsWhiteSpace()
|
|
? rsaPrivateKey.ExportPkcs8PrivateKey()
|
|
: rsaPrivateKey.ExportEncryptedPkcs8PrivateKey(
|
|
password.ToArray(),
|
|
new PbeParameters(
|
|
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
|
|
HashAlgorithmName.SHA1,
|
|
2000));
|
|
}
|
|
else
|
|
{
|
|
using ECDsa? ecdsaPrivateKey = certificate.GetECDsaPrivateKey();
|
|
if (ecdsaPrivateKey != null)
|
|
{
|
|
// write private key as PKCS#8
|
|
exportedPkcs8PrivateKey = password.IsEmpty || password.IsWhiteSpace()
|
|
? ecdsaPrivateKey.ExportPkcs8PrivateKey()
|
|
: ecdsaPrivateKey.ExportEncryptedPkcs8PrivateKey(
|
|
password.ToArray(),
|
|
new PbeParameters(
|
|
PbeEncryptionAlgorithm.TripleDes3KeyPkcs12,
|
|
HashAlgorithmName.SHA1,
|
|
2000));
|
|
}
|
|
}
|
|
}
|
|
|
|
// TODO: returns null content if neither RSA nor ECDsa private key is present.
|
|
return EncodeAsPEM(
|
|
exportedPkcs8PrivateKey ?? throw new CryptographicException("No private key found."),
|
|
password.IsEmpty || password.IsWhiteSpace() ? "PRIVATE KEY" : "ENCRYPTED PRIVATE KEY");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Returns a byte array containing the private key in PEM format.
|
|
/// </summary>
|
|
public static bool TryRemovePublicKeyFromPEM(
|
|
string thumbprint,
|
|
ReadOnlySpan<byte> pemDataBlob,
|
|
[NotNullWhen(true)] out byte[]? modifiedPemDataBlob)
|
|
{
|
|
modifiedPemDataBlob = null;
|
|
const string label = "CERTIFICATE";
|
|
string beginlabel = $"-----BEGIN {label}-----";
|
|
string endlabel = $"-----END {label}-----";
|
|
try
|
|
{
|
|
string pemText = Encoding.UTF8.GetString(pemDataBlob);
|
|
int searchPosition = 0;
|
|
int count = 0;
|
|
int endIndex = 0;
|
|
while (endIndex > -1 && count < 99)
|
|
{
|
|
count++;
|
|
int beginIndex = pemText.IndexOf(
|
|
beginlabel,
|
|
searchPosition,
|
|
StringComparison.Ordinal);
|
|
if (beginIndex < 0)
|
|
{
|
|
return false;
|
|
}
|
|
endIndex = pemText.IndexOf(endlabel, searchPosition, StringComparison.Ordinal);
|
|
beginIndex += beginlabel.Length;
|
|
if (endIndex < 0 || endIndex <= beginIndex)
|
|
{
|
|
return false;
|
|
}
|
|
string pemCertificateContent = pemText[beginIndex..endIndex];
|
|
var pemCertificateDecoded = new Span<byte>(
|
|
new byte[pemCertificateContent.Length]);
|
|
if (Convert.TryFromBase64Chars(
|
|
pemCertificateContent,
|
|
pemCertificateDecoded,
|
|
out int bytesWritten))
|
|
{
|
|
#if NET6_0_OR_GREATER
|
|
using X509Certificate2 certificate = X509CertificateLoader.LoadCertificate(
|
|
pemCertificateDecoded);
|
|
#else
|
|
using X509Certificate2 certificate = X509CertificateLoader.LoadCertificate(
|
|
pemCertificateDecoded.ToArray());
|
|
#endif
|
|
if (thumbprint.Equals(certificate.Thumbprint, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
int blockStart = beginIndex - beginlabel.Length;
|
|
int blockEnd = endIndex + endlabel.Length;
|
|
int blockLength = blockEnd - blockStart;
|
|
modifiedPemDataBlob = Encoding.ASCII.GetBytes(
|
|
pemText.Replace(
|
|
pemText.Substring(blockStart, blockLength),
|
|
string.Empty,
|
|
StringComparison.Ordinal));
|
|
return true;
|
|
}
|
|
}
|
|
|
|
searchPosition = endIndex + endlabel.Length;
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return false;
|
|
}
|
|
return false;
|
|
}
|
|
#endif
|
|
|
|
private static byte[] EncodeAsPEM(byte[] content, string contentType)
|
|
{
|
|
if (content == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(content));
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(contentType))
|
|
{
|
|
throw new ArgumentNullException(nameof(contentType));
|
|
}
|
|
|
|
const int lineLength = 64;
|
|
string base64 = Convert.ToBase64String(content);
|
|
using var textWriter = new StringWriter();
|
|
textWriter.WriteLine("-----BEGIN {0}-----", contentType);
|
|
|
|
int offset = 0;
|
|
while (base64.Length - offset > lineLength)
|
|
{
|
|
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
|
|
textWriter.WriteLine(base64.AsSpan(offset, lineLength));
|
|
#else
|
|
textWriter.WriteLine(base64.Substring(offset, lineLength));
|
|
#endif
|
|
offset += lineLength;
|
|
}
|
|
|
|
int length = base64.Length - offset;
|
|
if (length > 0)
|
|
{
|
|
#if NETSTANDARD2_1 || NET5_0_OR_GREATER
|
|
textWriter.WriteLine(base64.AsSpan(offset, length));
|
|
#else
|
|
textWriter.WriteLine(base64.Substring(offset, length));
|
|
#endif
|
|
}
|
|
|
|
textWriter.WriteLine("-----END {0}-----", contentType);
|
|
return Encoding.ASCII.GetBytes(textWriter.ToString());
|
|
}
|
|
}
|
|
}
|