Files
UA-.NETStandard/docs/KeyCredentialService.md
Marc Schier c4e0721a29 Add a documentation learning path and fix issues found while verifying it (#4555)
## Summary

### Documentation
- Stage the documentation index as a learning path: a first application,
independent client, server, and PubSub paths, then data and services,
companion models, production, advanced integration, and draft or
experimental capabilities.
- Add Getting started (repository samples or NuGet packages), OPC UA
concepts, Your first information model, and a production readiness
checklist.
- Add Native AOT application publishing, a first PubSub publisher and
subscriber exchange, and the UDP transport options.
- Add or expand contents navigation throughout `docs/`, and keep
contributor documentation separate.
- Correct outdated SDK examples and capability guidance, consolidate
repeated explanations into canonical guides, and repair local links and
heading structure.
- Rewrite What's New in 2.0 as a concise feature overview with short
linked details; keep migration instructions in the Migration Guide.
- Expand the feature catalogue with specification IDs, GDS, LDS, the OPC
10000-21 onboarding registrar, ISA-95, xRegistry, OpenUSD, and
sample-local models; distinguish draft status, explain crypto
pluggability, and bring performance guidance forward.
- Address review feedback on wording, active monitored items during
shadow reload, and the `Samples.md` filename and references.
- Regenerate the `opcua-v20-migration` plugin's bundled copy of the
migration guides so it matches the edited `docs/migrate/2.0.x` guides.
- Merge the latest `master`, preserving upstream resource-isolation
guidance within the task-based documentation index.
- Retain deferred Lingity findings where appropriate; this PR does not
claim that every document meets the Lingity score thresholds.

### Fixes found while verifying the guides
Each fix has regression tests that fail without it.
- **Client:** V2 subscriptions compared their lifetime with the
operation timeout instead of the session timeout, and logged a spurious
warning. `ISubscriptionEngineContext`, which is new in 2.0, gains a
`SessionTimeout` property; implementations must add it.
- **PubSub:** a subscriber now registers the `DataSetMetaData`
configured on its readers (OPC 10000-14 6.2.9.4), and the UADP decoder
decodes DataSetMessages that carry no ConfigurationVersion. Before, a
secured subscriber of the reference sample received no DataSets.
- **Source generator:** a ModelDesign method that declares its arguments
inline, without a method type, produced code that did not compile; it
now uses `MethodState`. The generated code of existing models is
unchanged.
- **MinimalClient sample:** waits for its first data-change notification
before it disconnects.

### Known issues, not addressed here
- UDP multicast: the publisher does not send on the interface that the
subscriber joins, and `MulticastLoopback` defaults to false. The PubSub
guide uses unicast for the exchange on one computer.
- The UDP metadata announcement is sent unsecured on secured writer
groups; a secured subscriber drops it with a warning.
- A server does not start in globalization-invariant mode, because
`ResourceManager` creates `CultureInfo("en-US")`. The Native AOT guide
cautions against the mode.

## Validation
- `git diff --check` and
`./.azurepipelines/validate-migration-plugin.ps1` (15 bundled migration
docs validated, plugin manifests synchronized).
- Local Markdown links, anchors, file-link casing, and contents lists
checked across all 87 documents under `docs/`. The index links every
top-level guide and every target of the previous index.
- Both Getting started routes, Your first information model, the PubSub
exchange, and the Native AOT publish of the Getting started client and
server were run as documented. The NuGet route and the tutorial use the
public `2.0.0-preview.5` packages.
- The changed libraries build for all target frameworks in Release
without warnings.
- Tests on .NET 10: Opc.Ua.SourceGeneration.Tests 199 passed;
Opc.Ua.SourceGeneration.Core.Tests 3,977 passed, 8 skipped;
Opc.Ua.Server.Tests `Fluent` category 621 passed; Opc.Ua.Client.Tests
subscription-engine tests 70 passed; Opc.Ua.PubSub.Tests 1,374 passed, 2
skipped; PubSub fuzz replay 145 passed. The new and affected tests also
pass on .NET Framework 4.8.
- Earlier merge validation: 174 resource-isolation tests passed on .NET
10.
- The full solution suite was not run locally.

Review and validation artifacts are maintained outside the repository.

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-09-28 19:19:39 +00:00

17 KiB

KeyCredentialService Developer Guide

OPC 10000-12 §8 defines the KeyCredentialService. A Global Discovery Server (GDS) uses it to issue and manage credentials, such as usernames and passwords, API keys, or tokens, for applications that authenticate to services outside OPC UA. Examples include Message Queuing Telemetry Transport (MQTT) brokers and REST APIs.

Scope note: This service issues credentials for resources outside OPC UA, such as MQTT brokers and REST APIs. See ResourceUri and ProfileUris on KeyCredentialServiceType. The optional bridge authenticator described below is EXPERIMENTAL under the vendor URI urn:opcfoundation:netstandard:profile:authentication:keycredential; it is not an OPC UA Part 6 §6.5.3 conformance claim. For standards-conformant OPC UA session authentication, use AuthorizationService with JSON Web Tokens (JWT) and the Identity Providers infrastructure.

Contents

Architecture

┌─────────────────┐     StartRequest      ┌────────────────────────┐
│  OPC UA Client   │ ──────────────────► │  ApplicationsNodeManager │
│  (or application)│ ◄────────────────── │  (GDS Server)            │
│                  │     FinishRequest    │                          │
│                  │ ──────────────────► │  ┌──────────────────────┐ │
│                  │     Revoke          │  │ IKeyCredentialRequest │ │
└─────────────────┘                      │  │       Store          │ │
                                         │  └──────────┬───────────┘ │
                                         │             │             │
                                         │  ┌──────────▼───────────┐ │
                                         │  │     ISecretStore     │ │
                                         │  └──────────────────────┘ │
                                         └────────────────────────────┘

Client API

KeyCredentialServiceClient

A thin client proxy for the three KeyCredentialService methods. Requires an active ISession and the NodeId of the KeyCredentialService instance in the server's address space.

using Opc.Ua.Gds.Client;

// After connecting a session to the GDS server:
var kcClient = new KeyCredentialServiceClient(session, serviceNodeId);

// 1. Request a new credential
NodeId requestId = await kcClient.StartRequestAsync(
    applicationUri: "urn:my-app",
    publicKey: myPublicKey,
    securityPolicyUri: null,         // server chooses
    requestedRoles: default);        // server chooses

// 2. Finish (collect) the credential
var (credentialId, credentialSecret, thumbprint, policyUri, grantedRoles)
    = await kcClient.FinishRequestAsync(requestId, cancelRequest: false);

// Use credentialId + credentialSecret to authenticate to the
// target service (MQTT broker, REST API, etc.)

// 3. Revoke when no longer needed
await kcClient.RevokeAsync(credentialId);

Discovering the Service NodeId

The KeyCredentialService instance is typically found under the server's Directory or ServerConfiguration node. Browse for objects of type KeyCredentialServiceType (namespace 0):

// Browse the server for KeyCredentialServiceType instances
var browser = new Browser(session);
// ... or use the well-known NodeId if your GDS exposes one.

Server-Side: Implementing a Provider

IKeyCredentialRequestStore

The server-side abstraction for the credential lifecycle:

public interface IKeyCredentialRequestStore
{
    // Begin a new credential request. Returns a request ID.
    NodeId StartRequest(
        string applicationUri,
        ByteString publicKey,
        string? securityPolicyUri,
        ArrayOf<NodeId> requestedRoles);

    // Complete or cancel a request. Returns issued credential data.
    KeyCredentialRequestState FinishRequest(
        NodeId requestId,
        bool cancelRequest,
        out string? credentialId,
        out ByteString credentialSecret,
        out string? certificateThumbprint,
        out string? securityPolicyUri,
        out ArrayOf<NodeId> grantedRoles);

    // Revoke a previously issued credential.
    void Revoke(string credentialId);
}

Built-in Implementation

InMemoryKeyCredentialRequestStore provides a ready-to-use in-process implementation. It auto-approves requests and generates random 32-byte secrets.

With ISecretStore integration — credential secrets are persisted through any ISecretStore backend (Key Vault, DPAPI, etc.):

// Use the default in-memory secret store
var store = new InMemoryKeyCredentialRequestStore();

// Or plug in a production secret store
ISecretStore vault = new MyKeyVaultSecretStore("KeyCredential");
var store = new InMemoryKeyCredentialRequestStore(vault);

Writing a Custom Implementation

For production systems with approval workflows:

public class DatabaseKeyCredentialStore : IKeyCredentialRequestStore
{
    private readonly IDbConnection _db;

    public NodeId StartRequest(
        string applicationUri,
        ByteString publicKey,
        string? securityPolicyUri,
        ArrayOf<NodeId> requestedRoles)
    {
        // 1. Insert a pending request into the database
        // 2. Return the generated request ID
        // 3. Optionally notify an admin for approval
        var id = _db.InsertPendingRequest(applicationUri, publicKey);
        return new NodeId(id);
    }

    public KeyCredentialRequestState FinishRequest(
        NodeId requestId,
        bool cancelRequest,
        out string? credentialId, ...)
    {
        var record = _db.GetRequest(requestId);
        if (record.State == "Pending")
        {
            // Still awaiting approval
            credentialId = null;
            // ... set other out params to defaults
            return KeyCredentialRequestState.New;
        }
        // Return the approved credential
        credentialId = record.CredentialId;
        // ...
        return KeyCredentialRequestState.Completed;
    }

    public void Revoke(string credentialId)
    {
        _db.RevokeCredential(credentialId);
        // Optionally notify the target service to invalidate
    }
}

Wiring into the GDS Server

Set the KeyCredentialRequestStore property on the ApplicationsNodeManager (done via GlobalDiscoverySampleServer or a custom server):

// In your INodeManagerFactory or server setup:
var appNodeManager = new ApplicationsNodeManager(server, configuration, ...);
appNodeManager.KeyCredentialRequestStore =
    new InMemoryKeyCredentialRequestStore(mySecretStore);

Decision matrix: Push vs Pull vs Bridge

Model Primary actor Use when Standard / conformance posture
Pull (KeyCredentialServiceType) Client/application asks a GDS to issue a credential. The GDS owns approval and issuance; the caller later retrieves the issued secret with FinishRequest. OPC 10000-12 §8 KeyCredentialService.
Push (KeyCredentialConfigurationFolderType) Administrator or provisioning agent writes credentials to a resource server. A resource server must store, rotate, or delete credentials locally through CreateCredential, UpdateCredential, and DeleteCredential. OPC 10000-12 §8 Push model; enabled with WithKeyCredentialPush().
Bridge (KeyCredentialBridgeAuthenticator) OPC UA client presents a KeyCredential proof as an issued identity token. Closed deployments need an interim bridge between GDS-issued secrets and UA session authentication. Experimental vendor extension only; not a Part 6 §6.5.3 conformance claim.

Hybrid (Push + Pull)

  • Enable both models when a GDS issues credentials (Pull) and hosts the Push subject. Admin tools can push freshly issued credentials to target resource servers in one round-trip.
  • For wiring in the same process, use services.AddOpcUa().AddGdsServer(...).WithKeyCredentialPush(). The Pull side stays on the GDS, and the Push side is enabled on the same node so admin clients write credentials directly to the GDS's resource-server view.
  • For wiring across processes, the GDS uses the default Pull path (InMemoryKeyCredentialRequestStore), while each resource server enables Push with WithKeyCredentialPush(). The admin tool reads from the GDS and writes to each resource server.
  • The bridge authenticator is independent of Push/Pull: it lets the resource server accept KeyCredential blobs as a UA identity. The hybrid model addresses issuance and distribution; the bridge addresses consumption.

Resource Server Push Binding

A regular OPC UA resource server can opt in to the Part 12 §8 Push model with WithKeyCredentialPush(). The binding mounts on the standard ServerConfiguration/KeyCredentialConfiguration folder by default and stores secrets through IKeyCredentialStore (default: InMemoryKeyCredentialStore backed by ISecretStore).

using Microsoft.Extensions.DependencyInjection;
using Opc.Ua;
using Opc.Ua.Server.Hosting;

services.AddOpcUa()
    .AddServer(options =>
    {
        options.ApplicationUri = "urn:my-resource-server";
        options.ProductUri = "uri:my-company:resource-server";
        options.EndpointUrls.Add("opc.tcp://localhost:4840");
    })
    .WithKeyCredentialPush();

Production deployments should register an IKeyCredentialStore backed by a durable secret store before calling WithKeyCredentialPush().

The standard folder remains in namespace 0. Created and restored credential instances use a nonstandard namespace owned by the binding node manager (the diagnostics namespace for ConfigurationNodeManager), so their properties and methods are addressable through Read, Browse, and Call. Descendant NodeIds are allocated per instance through the configured factory, so creating another credential does not alias an existing credential's properties. Use the returned CredentialNodeId and browse its children rather than assuming a namespace index. A custom folder keeps its own namespace; standalone bindings using KeyCredentialPushSubject.NamespaceUri must register that namespace with their hosting node manager.

GetEncryptingKey returns an application certificate from the server's active certificate registry. UpdateCredential decrypts a UA Binary RsaEncryptedSecret before passing the usable secret to IKeyCredentialStore. It verifies the declared policy, certificate thumbprint, envelope, signature and timestamp; invalid input never reaches the store. Both methods require the SecurityAdmin role and an encrypted SecureChannel. The envelope nonce is deliberately not compared with a session nonce: outside ActivateSession, OPC UA Part 4 Table 185 requires the receiver not to check it.

The push binding accepts Basic256Sha256, Aes128_Sha256_RsaOaep and Aes256_Sha256_RsaPss. Restrict or reorder these through KeyCredentialPushOptions.AllowedSecurityPolicyUris; the first entry is the default for GetEncryptingKey. ECC/RSA-DH policies are explicitly rejected with BadSecurityPolicyRejected: this binding does not provide the required ephemeral-key exchange. Omitting the policy and certificate thumbprint retains the standard clear-secret-over-encrypted-channel mode. Supplying a policy never causes ciphertext to be stored as if it were a plaintext secret.

For direct construction, the original constructor remains available and ConfigurationNodeManager.BindKeyCredentialPushAsync supplies the server's registry. A standalone caller can instead pass an ICertificateRegistry and ISecurityPolicyRegistry to the additional constructor. Temporary decode buffers are cleared; the credential record handed to a custom store remains valid if that store retains it.

Experimental KeyCredential Issued-Token Bridge

WARNING — EXPERIMENTAL: KeyCredentialBridgeAuthenticator is a vendor extension under urn:opcfoundation:netstandard:profile:authentication:keycredential. It is not a Part 6 §6.5.3 conformance claim. Deployments that claim OPC UA conformance MUST NOT use this bridge as their standards-conformant user-token mechanism. Use it only in closed deployments where the GDS, resource server, and clients are controlled by the same operator.

The bridge lets a server validate a JSON issued-token payload containing a credentialId, nonce timestamp, and HMAC proof. The server looks up the credential in IKeyCredentialStore, validates the proof with the stored secret, and returns an identity populated from the credential's subject claims.

Client-side, GdsKeyCredentialAccessTokenProvider adapts a KeyCredentialServiceClient to IAccessTokenProvider, so the standard IssuedTokenIdentityProvider can materialize a UA IssuedIdentityToken for the bridge profile.

The bridge token payload carries a "version" field. It versions this vendor extension's own JSON payload, and has no OPC UA counterpart: Part 6 §6.5.3 and the GDS KeyCredential services define neither this payload nor a version field. The server accepts "version": 2 only, whose HMAC proof covers a non-empty aud that must exactly match the resource server's ApplicationUri, so a proof minted for one server is rejected by another.

The provider implements IEndpointAccessTokenProvider. Normal identity selection forwards the selected endpoint automatically, including for the vendor bridge profile. The audience is the first non-blank value of metadata Audience, metadata ResourceUri, or endpoint.Server.ApplicationUri. Thus a policy containing only {"authorityUri":"urn:example:gds"} still binds the proof to the target resource server, never to the GDS authority or client application. Explicit audience/resource metadata must identify that same server.

var identities = new IssuedTokenIdentityProvider(
    keyCredentialProvider, GdsKeyCredentialAccessTokenProvider.ProfileUri);

// Direct acquisition outside normal identity selection also supplies the target.
using AccessToken token = await keyCredentialProvider.AcquireAsync(
    metadata, targetEndpoint, cancellationToken);

The metadata-only acquisition overload requires an explicit non-blank audience or resource URI. If none is available, acquisition fails before requesting or reading credential secrets instead of emitting an unusable unbound token.

Audit Events

All KeyCredentialService operations emit audit events automatically:

Operation Audit Event Type
StartRequest KeyCredentialRequestedAuditEventType
FinishRequest KeyCredentialDeliveredAuditEventType
Revoke KeyCredentialRevokedAuditEventType

Credential secrets are never included in audit payloads.

End-to-End Example

// ── Server Side ──────────────────────────────────────

// 1. Create the credential store
var secretStore = new InMemorySecretStore("KeyCredentials");
var kcStore = new InMemoryKeyCredentialRequestStore(secretStore);

// 2. Create the GDS server with credential support
var gdsServer = new GlobalDiscoverySampleServer(
    database, requestStore, certGroup, userDb, telemetry);

// 3. After server starts, wire the store
// (done automatically by ApplicationsNodeManager when
//  KeyCredentialRequestStore is set before CreateAddressSpace)

// ── Client Side ──────────────────────────────────────

// 1. Connect to the GDS
var gdsClient = new GlobalDiscoveryServerClient(config);
await gdsClient.ConnectAsync(gdsEndpointUrl);

// 2. Find the KeyCredentialService node
// (browse or use a well-known NodeId)

// 3. Create the client proxy
var kcClient = new KeyCredentialServiceClient(
    gdsClient.Session, serviceNodeId);

// 4. Request → Finish → Use → Revoke
NodeId reqId = await kcClient.StartRequestAsync(
    "urn:my-mqtt-bridge", default, null, default);

var (credId, secret, _, _, _) =
    await kcClient.FinishRequestAsync(reqId, false);

// Use credId/secret to connect to MQTT broker...

// When done:
await kcClient.RevokeAsync(credId);