Skip to content

Secrets (OrchardCore.Secrets)

The Secrets module provides a secure, centralized way to store and manage sensitive data such as passwords, API keys, connection strings, and certificates. It addresses common challenges in managing secrets across development, staging, and production environments.

The following video explains why the Secrets module exists, walks through each of its features, and shows how to adopt it in your own modules.

Why Use the Secrets Module?

The Problem

Orchard Core modules need a comprehensive, consistent way to store, retrieve, and manage secrets. Without a shared abstraction, each module must invent its own solution for credential storage, encryption, configuration, and deployment, leading to duplicated code and inconsistent behavior.

Managing sensitive configuration in web applications presents several challenges:

  1. Security Risks: Storing passwords and API keys in appsettings.json or environment variables can lead to accidental exposure through source control, logs, or configuration dumps.

  2. Deployment Complexity: When using deployment plans or recipes to set up new tenants, secrets cannot be included directly without compromising security.

  3. Multi-Environment Management: Different environments (development, staging, production) often need different secrets, making configuration management complex.

  4. Certificate Management: Storing certificates for OpenID Connect, signing tokens, or SSL can be problematic, especially in multi-server deployments where file-based certificates aren't accessible.

  5. Audit and Rotation: Without a centralized secret store, it's difficult to track who accessed secrets or rotate them across all services.

The Solution

The OrchardCore.Secrets.Abstractions project defines the shared contracts for secrets management, including ISecretManager, ISecretStore, and ISecretTypeProvider, along with secret types and metadata. Modules can depend on these abstractions to consume secrets without coupling their code to a particular storage implementation.

The Secrets module provides:

  • Encrypted Storage: All secrets are encrypted using ASP.NET Core Data Protection before being stored in the database.
  • Centralized Management: A single admin UI to view, create, update, and delete all secrets.
  • Multiple Backends: Support for database storage (default) and Azure Key Vault for enterprise scenarios.
  • Deployment Support: Export secret metadata (not values) and import secrets from environment variables during setup.
  • Type Safety: Different secret types (text, RSA keys, X.509 certificates) with appropriate handling for each.

Common Use Cases

1. SMTP Email Credentials

Store your email server password securely instead of in configuration files:

// In your email service
var passwordSecret = await _secretManager.GetSecretAsync<TextSecret>("Email.SmtpPassword");
var password = passwordSecret?.Text;

2. Third-Party API Keys

Manage API keys for services like payment gateways, analytics, or social media:

// Store API keys with descriptive names
await _secretManager.SaveSecretAsync("Stripe.SecretKey", new TextSecret { Text = "sk_live_..." });
await _secretManager.SaveSecretAsync("SendGrid.ApiKey", new TextSecret { Text = "SG...." });
await _secretManager.SaveSecretAsync("Google.MapsApiKey", new TextSecret { Text = "AIza..." });

3. OpenID Connect Signing Keys

Store RSA keys for JWT token signing without filesystem dependencies:

// Generate and store signing keys
var rsaSecret = new RsaKeySecret 
{ 
    IncludesPrivateKey = true,
    PublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey()),
    PrivateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey())
};
await _secretManager.SaveSecretAsync("OpenId.SigningKey", rsaSecret);

4. Database Connection Strings

Protect database credentials, especially for production environments:

var connectionSecret = await _secretManager.GetSecretAsync<TextSecret>("Database.ConnectionString");
var connectionString = connectionSecret?.Text ?? defaultConnectionString;

5. Multi-Tenant SaaS Deployments

When deploying new tenants with recipes, define which secrets are needed without exposing values:

Recipe file (safe to commit):

{
  "steps": [
    {
      "name": "Secrets",
      "Secrets": [
        { "Name": "Smtp.Password" },
        { "Name": "Payment.ApiKey" },
        { "Name": "Analytics.TrackingId" }
      ]
    }
  ]
}

Environment variables (set during deployment):

env 'OrchardCore__Secrets__Smtp.Password=actual-password' \
    'OrchardCore__Secrets__Payment.ApiKey=actual-api-key' \
    'OrchardCore__Secrets__Analytics.TrackingId=UA-12345' \
    dotnet OrchardCore.Cms.Web.dll

6. Azure Key Vault for Production

For production environments, use Azure Key Vault for hardware-backed security and centralized secret management:

{
  "AzureClients": {
    "SecretClient": {
      "VaultUri": "https://mycompany-prod.vault.azure.net/",
      "Credential": {
        "CredentialSource": "ManagedIdentityCredential",
        "ManagedIdentityIdKind": "SystemAssigned"
      }
    }
  },
  "OrchardCore": {
    "Secrets": {
      "AzureKeyVault": {
        "AzureClient": "SecretClient",
        "NamePrefix": "mycompany"
      }
    }
  }
}

Register the named client in the host as shown in Azure Key Vault Store. With Managed Identity, no credential secrets are needed in configuration—Azure handles authentication automatically.

Features

  • Secure storage of sensitive data using ASP.NET Core Data Protection
  • Multiple secret store providers (database, Azure Key Vault)
  • Three secret types: Text, RSA Keys, and X.509 Certificates
  • Admin UI for managing secrets, secret stores, and the credentials kept by other features
  • A <secret-input> tag helper that lets any settings screen keep a credential in its own settings, or in the Secrets module, see Adding Secret Support to Your Own Credentials
  • ViewComponent for selecting secrets in other module UIs
  • Recipe support for importing secrets during setup
  • Deployment step for exporting secret metadata

Getting Started

Enabling the Feature

  1. Navigate to Admin → Configuration → Features
  2. Search for "Secrets"
  3. Click Enable on the "Secrets" feature

Enabling the Secrets feature

Accessing the Secrets Admin

Once enabled, the Secrets admin is available under the Tools → Security menu:

  1. In the admin sidebar, click Tools to expand the menu
  2. Click Security
  3. Click Secrets to manage the secrets, Secret Stores to move secrets between stores, or Migrate Secrets to move the credentials kept in the settings of other features to secrets

Secrets menu location

Managing Secrets

Viewing Secrets

The Secrets index page lists the stored secrets like the other admin lists. Each entry shows its name and description, with badges for its type, its store, its expiration, and when it was last updated. Use the search box to find secrets by name, description, type, or store, and the filters of the list header to show the secrets that have expired, expire within 30 days, or never expire, or the secrets of a type, such as Text Secret. Clicking the type badge of a secret also shows the secrets of that type. The list is paged, and the page size can be changed when the site settings allow it. Select several secrets to delete them at once with the Actions menu.

Secrets list

Creating a Secret

  1. Click Add Secret on the Secrets index page
  2. Select the type of secret (e.g., Text Secret)
  3. Fill in the fields:
  4. Name: A unique name for the secret (e.g., Smtp.Password, ApiKey). Settings reference secrets by this name, so it cannot be changed later.
  5. Store: The store that keeps the secret, when several writable stores are enabled
  6. Value: The actual secret value (will be encrypted before storage)
  7. Description: Optional description for documentation purposes
  8. Click Save

Create secret form

Editing a Secret

  1. Click Edit next to the secret you want to modify. The page title shows the name of the secret, which cannot be changed, and the store that keeps it.
  2. Update the fields as needed
  3. Note: The secret value field is empty for security. Leave it empty to keep the existing value, or enter a new value to update it.
  4. Click Save

Edit secret form

Deleting a Secret

  1. Click Delete next to the secret you want to remove
  2. Confirm the deletion in the dialog

Moving Secrets and Retiring a Store

Use Move on an individual entry, or Tools → Security → Secret Stores to transfer every active entry of a store: select the Source store, which shows the total number of active secrets it keeps, then the destination store under Move all active secrets from this store to. The move section is only shown when the source store keeps active secrets, and when another writable store is enabled. Select a different writable destination and confirm. The operation retains logical names, types, descriptions, and expiration dates, verifies the committed destination value and metadata, and then removes only the selected source copy. Values never pass through the management form, response, or an export file. X.509 entries move references only.

Destination collisions are rejected, not overwritten. Bulk transfers are not atomic: review each result, especially failures with a saved destination copy, before retrying or deleting a remaining source. Verification failures retain the source. Normal secret-manager writes and store operations share a tenant lock; configure a distributed lock provider for multiple instances and pause direct store writes, rotation, and provider changes while transferring.

Secret Stores displays the total number of active secrets in the selected store of the current tenant. Successful moves remove the source using the provider's existing RemoveSecretAsync operation. The existing Delete action also removes only the selected secret/store and can break consumers if no destination copy exists. No new purge interface or purge action is provided.

Inspect every affected tenant, ensure the active-secret count is zero, and verify destination consumers after restart before disabling an optional provider. If inspection fails, cleanup status is unknown, not empty. The database store cannot be disabled independently of the base Secrets feature. Transfers do not change the default writable store: select the destination explicitly when creating or saving later secrets and recheck the source before retirement.

Key Vault deletion remains recoverable under its soft-delete policy and retains old versions; Orchard does not purge those values. Database removal does not erase backups or transaction logs. External copies, audit history, and provider retention also remain outside this operation. Rotate/revoke credentials when historical copies must no longer work. See the 4.0 store cleanup instructions.

Programmatic operations return metadata-only per-secret results:

// Resolve ISecretStoreOperations from the current tenant's services.
var result = await operations.MoveSecretAsync("Payment.ApiKey", "Database", "AzureKeyVault");
var results = await operations.MoveAllSecretsAsync("Database", "AzureKeyVault");
// Delete one remaining source copy only after reviewing a partial transfer.
await secretManager.RemoveSecretAsync("Payment.ApiKey", "Database");

Store SaveSecretAsync and RemoveSecretAsync implementations must complete only after persistence, not after merely staging a write. Built-in database mutations use a separate tenant scope to commit the secret change before releasing the mutation lock, without committing unrelated caller changes.

Moving Credentials from Settings to Secrets

Features that use a credential, such as the SMTP password or an external login client secret, can keep it encrypted in their own settings, which works without the Secrets module. To move these credentials to secrets on demand:

  1. Go to Tools → Security → Migrate Secrets.
  2. The page lists every credential that is kept in the settings of an enabled feature and that does not already reference a secret. Select the ones to move, and adjust the name of each new secret if needed.
  3. Select the Destination store when several writable stores are enabled, then click Move to Secrets.

Each selected value is decrypted with its original Data Protection purpose, saved as a TextSecret, and the settings then reference the new secret and no longer keep the value. A secret with the same name is never overwritten, and a credential that cannot be decrypted or saved is reported and left unchanged in its settings. Only users who can manage both the secrets and the settings of a feature see its credentials.

Each feature contributes its credentials through a display driver of SecretMigration, see Step 7.

Secret Expiration

Secrets can have an optional expiration date. This is an informational feature designed to help with secret rotation planning:

  • Purpose: Track when secrets should be rotated or renewed
  • Behavior: Expired secrets continue to work - expiration does not automatically disable them
  • Expiration Warning: Users with the View Secrets or Manage Secrets permission, whatever their roles, see a warning on the admin dashboard when secrets have expired or expire within 30 days, with counts and a link to review the secrets. The Secrets list shows the same warning under its title. Other admin pages, and users without the permission, don't see it. The warning uses metadata only and does not expose secret names or values.
  • List-Page Visual Indicators:
  • Expired secrets show a red "Expired" badge
  • Secrets expiring within 30 days show a yellow "Expires" badge
  • Other secrets show their expiration date, or "Never expires"

Use Cases for Expiration:

  1. API Key Rotation: Set expiration to remind when to rotate third-party API keys
  2. Certificate Renewal: Track when X.509 certificates need to be renewed
  3. Compliance: Meet regulatory requirements for periodic credential rotation
  4. Automation: External systems can query secret metadata to trigger rotation workflows

To set an expiration date, use the "Expiration Date" field in the secret editor. Leave it empty for secrets that don't expire.

Configuration

Database Store (Default)

The database store is enabled by default when the Secrets module is enabled. It uses ASP.NET Core Data Protection to encrypt secrets before storing them in the database.

Azure Key Vault Store

To use Azure Key Vault as a secret store, enable the OrchardCore.Secrets.AzureKeyVault feature, register a named SecretClient in the application host, and select its service key in OrchardCore:Secrets:AzureKeyVault:AzureClient:

{
  "AzureClients": {
    "SecretClient": {
      "VaultUri": "https://your-vault.vault.azure.net/",
      "Credential": {
        "CredentialSource": "ManagedIdentityCredential",
        "ManagedIdentityIdKind": "SystemAssigned"
      },
      "Options": {
        "Retry": {
          "MaxRetries": 3,
          "Delay": "00:00:00.800",
          "MaxDelay": "00:01:00",
          "Mode": "Exponential",
          "NetworkTimeout": "00:01:40"
        },
        "Diagnostics": {
          "ApplicationId": "my-app",
          "IsLoggingEnabled": true,
          "IsTelemetryEnabled": true,
          "IsDistributedTracingEnabled": true,
          "IsLoggingContentEnabled": false,
          "LoggedContentSizeLimit": 4096,
          "AdditionalLoggedHeaderNames": [],
          "AdditionalLoggedQueryParameters": []
        },
        "DisableChallengeResourceVerification": false
      }
    }
  },
  "OrchardCore": {
    "Secrets": {
      "AzureKeyVault": {
        "AzureClient": "SecretClient",
        "NamePrefix": "myapp"
      }
    }
  }
}

Register the client before building the host, using the Azure SDK's configuration and dependency injection support:

using Azure.Identity;
using Azure.Security.KeyVault.Secrets;

#pragma warning disable SCME0002 // Azure SDK configuration support is experimental.
builder.AddKeyedAzureClient<SecretClient, SecretClientSettings>(
    "SecretClient", "AzureClients:SecretClient");
#pragma warning restore SCME0002

Here builder is an IHostApplicationBuilder. The service key (SecretClient) is independent of the configuration path (AzureClients:SecretClient); AzureClient must match the service key exactly. JSON configuration alone does not register a client. The module only resolves an existing keyed registration; it does not construct clients, choose credentials, or fall back to an unkeyed client. Missing or blank names, unregistered clients, and the reserved alias key OrchardCore.Secrets.AzureKeyVault fail explicitly.

SecretClientSettings binds the global client configuration, including VaultUri, Credential, and Options. Select an appropriate token credential in the host configuration. Key Vault does not support API-key authentication.

CredentialSource Credential settings Usage
ManagedIdentityCredential Omit identity settings for system-assigned identity; use ManagedIdentityIdKind: "ClientId" and ManagedIdentityId for a user-assigned client ID Azure managed identity.
WorkloadIdentityCredential TenantId, ClientId, and TokenFilePath or the corresponding Azure SDK environment Federated workload identity, such as an Azure Kubernetes Service workload.
EnvironmentCredential TenantId, ClientId, and ClientSecret, or equivalent Azure SDK environment variables Application credentials supplied through secure configuration.
AzureCliCredential An authenticated Azure CLI session Local development using only Azure CLI credentials.
AzurePowerShellCredential An authenticated Azure PowerShell session Local development using only Azure PowerShell credentials.
VisualStudioCredential An authenticated Visual Studio account Local development using only Visual Studio credentials.

These are common sources; the SDK supports additional sources and explicitly configured chains. See its configuration reference for source-specific properties. DefaultAzureCredential is not a CredentialSource supported by the SDK's configuration resolver; select the intended source, such as EnvironmentCredential, rather than the former module-specific CredentialType setting.

For production web applications, use a deterministic provider as recommended in Azure authentication best practices. Specific providers do not fall back to another identity after authentication fails. Host-registered singleton clients are shared across tenant containers; each tenant's store retains its own namespace.

For client secret authentication, provide Credential:ClientSecret through a secure configuration source, for example the AzureClients__SecretClient__Credential__ClientSecret environment variable, rather than storing it in appsettings.json.

Options is the SDK's SecretClientOptions configuration section, including DisableChallengeResourceVerification, nested Retry settings, and nested Diagnostics settings. Credential-specific settings, such as AuthorityHost and DisableInstanceDiscovery, belong under Credential. Omitted settings retain SDK defaults. Do not enable diagnostics content logging for secrets. The underlying SDK configuration APIs are currently experimental (SCME0002); host registration must opt in locally.

The feature registers a lazy keyed singleton alias with key OrchardCore.Secrets.AzureKeyVault, exposed as AzureKeyVaultSecretStore.SecretClientServiceKey. Resolving that alias returns the exact host-registered client selected by the tenant's AzureClient option, without changing its credentials or options. Other features can select the same host key to share a client, or select a different key to use another vault. To consume this feature's selected client from a tenant service:

public MyService(
    [FromKeyedServices(AzureKeyVaultSecretStore.SecretClientServiceKey)] SecretClient client)
{
    _client = client;
}

This requires Microsoft.Extensions.DependencyInjection, Azure.Security.KeyVault.Secrets, and OrchardCore.Secrets.AzureKeyVault. Each tenant resolves its own alias to the shared host client. Programmatic resolution uses GetRequiredKeyedService<SecretClient>(AzureKeyVaultSecretStore.SecretClientServiceKey).

NamePrefix defines an application namespace even for single-tenant sites. It defaults to oc; use a distinct prefix for each application sharing a vault. Prefixes must be nonblank and no longer than 256 characters.

Key Vault names combine a normalized readable prefix, Orchard tenant name, and logical secret name with a 24-character hexadecimal SHA-256 suffix. For example, myapp-default-payment-apikey-<hash> represents Payment.ApiKey in the Default tenant with prefix myapp. The readable portion uses lowercase ASCII letters, digits, and hyphens, and is truncated as needed to keep the entire name within Key Vault's 127-character limit. The 96-bit hash covers the exact, unambiguously encoded (prefix, tenant name, logical secret name) tuple, so names differing only by case, punctuation, or truncated characters remain distinct.

The store records the exact prefix, tenant name, original secret name, registered secret type, and description in tags. Reads, updates, and deletes validate ownership metadata; listing includes only entries matching the configured prefix and tenant. Credential:TenantId is the Microsoft Entra tenant ID, not the Orchard tenant name. Changing NamePrefix or renaming an Orchard tenant changes its namespace; plan an explicit secret migration before doing so.

These namespaces prevent accidental cross-tenant access through the store but are not an Azure authorization boundary: code with the vault credentials can bypass them. Use separate vaults or appropriately restricted identities for mutually untrusted tenants. Entries created outside Orchard without ownership tags are not automatically adopted. Create entries through the tenant's secret manager.

Deletion is a normal Key Vault soft delete. It never purges secrets, so purge permission is not required and purge protection remains effective. Azure's retention rules may prevent reusing a deleted name until it is recovered or its retention period ends.

The store is immutable when editing a secret in the admin UI. Edit and delete operations target the displayed store only. Clearing a description or expiration explicitly removes that metadata; programmatic saves without a SecretSaveOptions object preserve it.

Local development with the Azure Key Vault Emulator

The James Gould Azure Key Vault Emulator supports the Azure SDK clients used by this store. It is for local development and testing only, not production. Its documented client setup uses DefaultAzureCredential, not an API key.

Follow the emulator's setup instructions to start it and trust its TLS certificate. Use a version supporting its OAuth endpoints, as documented in the emulator's authentication and client configuration. For Docker, expose container port 4997 on a fixed host port. If persistence is enabled, keep that port unchanged: persisted entries contain the vault URI. For Aspire, enable persistence only with a fixed Port.

Enable OrchardCore.Secrets and OrchardCore.Secrets.AzureKeyVault for the Orchard tenant, register the named client in the host as shown above, and add the following to appsettings.Development.json. The SDK's configuration resolver selects EnvironmentCredential, the environment authentication source used by the emulator's documented DefaultAzureCredential setup. No emulator-specific mode or custom module is needed:

{
  "AzureClients": {
    "SecretClient": {
      "VaultUri": "https://localhost:4997",
      "Credential": {
        "CredentialSource": "EnvironmentCredential",
        "DisableInstanceDiscovery": true
      },
      "Options": {
        "DisableChallengeResourceVerification": true
      }
    }
  },
  "OrchardCore": {
    "Secrets": {
      "AzureKeyVault": {
        "AzureClient": "SecretClient",
        "NamePrefix": "localdev"
      }
    }
  }
}

Replace 4997 with the host port exposed by your emulator. EnvironmentCredential needs the emulator's credential environment. If you use Aspire, the emulator's WithAzureKeyVaultEmulatorCredentials integration supplies this automatically. For a standalone emulator, set these variables in the process that launches Orchard:

export AZURE_TENANT_ID=a0c2a3f5-e1b3-4d6a-9c41-2cdd1f2c7e0f
export AZURE_CLIENT_ID=a0c2a3f5-e1b3-4d6a-9c41-2cdd1f2c7e0f
export AZURE_CLIENT_SECRET=emulator-client-secret
export AZURE_AUTHORITY_HOST=https://localhost:4997

These are the emulator's public placeholder credentials, not real Azure credentials. Its OAuth endpoint accepts them locally; no Azure subscription or CLI login is needed. Never send real production credentials to an emulator. Alternatively, set TenantId, ClientId, ClientSecret, and AuthorityHost directly under Credential.

AZURE_AUTHORITY_HOST must point to the emulator's HTTPS endpoint rather than Microsoft's identity service. Alternatively, set Credential:AuthorityHost in the configuration section. The SDK does not infer the identity authority from VaultUri.

The emulator's localhost hostname requires Options:DisableChallengeResourceVerification to be true. Its local identity authority requires Credential:DisableInstanceDiscovery to be true. TLS certificate validation remains enabled: trust the emulator certificate rather than bypassing validation.

Keep these overrides in development configuration. Leave challenge-resource verification and identity instance discovery enabled for production Azure endpoints; both disabling flags default to false. No environment-based behavior or automatic emulator detection changes these settings.

To check the integration, create a text secret in the admin UI with AzureKeyVault selected as its store, then edit and delete it. For a programmatic read, use GetSecretAsync<TextSecret>(name, "AzureKeyVault") so a database entry cannot mask a failed emulator lookup. If persistence is enabled, restart the emulator on the same port and verify the secret is still readable before deleting it. Create secrets through Orchard rather than directly seeding bare emulator entries: the store requires its tenant, namespace, and type ownership tags.

Using Secrets Programmatically

Retrieving a Secret

public class MyService
{
    private readonly ISecretManager _secretManager;

    public MyService(ISecretManager secretManager)
    {
        _secretManager = secretManager;
    }

    public async Task UseSecretAsync()
    {
        var secret = await _secretManager.GetSecretAsync<TextSecret>("MyApiKey");
        if (secret != null)
        {
            var apiKey = secret.Text;
            // Use the API key
        }
    }
}

Saving a Secret

var secret = new TextSecret { Text = "my-secret-value" };
await _secretManager.SaveSecretAsync("MyApiKey", secret);

Saving to a Specific Store

// Save to Azure Key Vault specifically
await _secretManager.SaveSecretAsync("MyApiKey", secret, "AzureKeyVault");

Recipe Step

Secrets can be imported using a recipe step. Note that for security reasons, you should provide secret values via environment variables rather than directly in the recipe file.

Recipe Format

{
  "steps": [
    {
      "name": "Secrets",
      "Secrets": [
        {
          "Name": "SmtpPassword",
          "Store": "Database"
        },
        {
          "Name": "ApiKey",
          "Store": "AzureKeyVault"
        }
      ]
    }
  ]
}

Providing Secret Values

Secret values should be provided through the OrchardCore:Secrets:{SecretName} configuration key. For environment variables, use double underscores as hierarchy separators:

  • OrchardCore__Secrets__SecretName (environment variable)
  • OrchardCore:Secrets:SecretName (configuration key)

For example:

export OrchardCore__Secrets__SmtpPassword=mypassword
export OrchardCore__Secrets__ApiKey=myapikey

Secret names are matched exactly. A dot in a name such as Smtp.Password is not a configuration hierarchy separator; retain it in the environment variable name as shown in the deployment example above. Recipe values are read from application configuration, separately from the tenant-scoped Azure provider options.

Deployment Step

The Secrets Deployment Step allows you to export secrets as part of a deployment plan. This is useful for migrating secrets between tenants or environments.

Basic Export (Metadata Only)

By default, secrets are exported without their values for security. The import process then reads values from environment variables:

{
  "name": "Secrets",
  "Secrets": {
    "SmtpPassword": {
      "SecretInfo": {
        "Store": "Database",
        "Type": "TextSecret",
        "Description": null,
        "ExpiresUtc": null
      }
    }
  }
}

Encrypted Export

For scenarios where you need to transfer actual secret values (e.g., tenant migration, environment cloning), you can use encrypted export with RSA or X509 keys.

How It Works

Export does not contact the destination server or discover its public key. Before exporting, provision the destination's public key on the source and the corresponding private key on the destination. EncryptionKeyName is a logical secret name resolved independently in each tenant, not a destination URL. Only the public key needs to be shared with the source.

  1. Export: Secrets are encrypted using RSA+AES hybrid encryption
  2. A random AES-256 key is generated for each secret
  3. The secret value is encrypted with AES-GCM using a random 96-bit nonce and a 128-bit authentication tag
  4. The secret name, store, type, description, and expiration are authenticated as associated data
  5. The AES key is encrypted with RSA-OAEP-SHA256
  6. Import: On the target system
  7. The AES key is decrypted using RSA private key
  8. The authentication tag and metadata are verified before the secret value is deserialized
  9. The decrypted secret is saved to the secrets store

Setting Up Encryption Keys

Option 1: Using RsaKeySecret (Recommended)

Generate the key pair once on the destination, using its tenant's ISecretManager:

using var rsa = RSA.Create(2048);
var deploymentKey = new RsaKeySecret
{
    PublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey()),
    PrivateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey()),
    IncludesPrivateKey = true,
};
await _secretManager.SaveSecretAsync("Deployment.EncryptionKey", deploymentKey);

Copy the Base64 PublicKey to the source through a trusted channel. On the source, provision a public-key-only secret with the same logical name:

var deploymentKey = new RsaKeySecret
{
    PublicKey = destinationPublicKey,
    IncludesPrivateKey = false,
};
await _secretManager.SaveSecretAsync("Deployment.EncryptionKey", deploymentKey);

Here, destinationPublicKey is the exact Base64 public key from the destination, not a newly generated key. Do not generate independent key pairs on both systems: the public and private keys must match. Never copy the destination's private key to the source or include it in the deployment recipe.

The admin RSA creation page can generate a key pair on the destination, but it does not provide a complete public-key transfer/import workflow. Use the service-based provisioning above when configuring a public-key-only source. The selected encryption-key secret is excluded from the deployment export; it must already exist on the destination before encrypted secrets can be imported, including when using a setup recipe.

Option 2: Using X509Secret

Use an RSA-capable X.509 certificate, with an X509Secret under the same logical name in each tenant:

  • PEM-encoded certificate: on the destination, create the secret with the PEM-encoded certificate and its private key. On the source, create it with the PEM-encoded certificate only. No certificate store is involved.
  • Certificate store: install the public certificate on the source and the matching certificate with its private key on the destination, then create the secret pointing to that machine's certificate store location, store name, and thumbprint. Ensure the destination application's identity can access the certificate's private key.

In both cases, the source needs only the public key.

Creating an Encrypted Export

  1. Go to Configuration → Import/Export → Deployment Plans
  2. Create or edit a deployment plan
  3. Add a Secrets step
  4. In the Encryption Key dropdown, select your encryption key (e.g., Deployment.EncryptionKey)
  5. Execute the deployment plan

Export runs on the source and reads its local key secret. No destination key-discovery endpoint is invoked.

The exported JSON will contain encrypted secret values:

{
  "name": "Secrets",
  "EncryptionKeyName": "Deployment.EncryptionKey",
  "Secrets": {
    "SmtpPassword": {
      "SecretInfo": {
        "Store": "Database",
        "Type": "TextSecret",
        "Description": null,
        "ExpiresUtc": null
      },
      "Version": 1,
      "EncryptedKey": "BASE64_RSA_ENCRYPTED_AES_KEY...",
      "EncryptedData": "BASE64_AES_ENCRYPTED_SECRET...",
      "IV": "BASE64_GCM_NONCE...",
      "Tag": "BASE64_GCM_TAG..."
    }
  }
}

Version 1 envelopes use authenticated encryption. Envelopes with an unsupported version or missing authentication tag are rejected. Do not edit names, store names, types, descriptions, or expiration dates in an encrypted recipe: changes invalidate authentication. A failed encrypted export fails the deployment instead of emitting a metadata-only fallback. Duplicate logical names across stores must be resolved before export.

Export and import use registered ISecretTypeProvider instances, including custom types. Providers can override Serialize and Deserialize for their own wire format; the default implementation uses JSON for the provider's concrete CLR type. Register the same provider on the source and destination.

Importing Encrypted Secrets

  1. Ensure the encryption key exists on the target system with the private key
  2. Import the recipe using standard methods (Import/Export, setup recipe, or API)
  3. The recipe step will:
  4. Look up the encryption key by name
  5. Decrypt each secret
  6. Save to the secrets store

The destination needs the matching private key, the registered secret type providers, and the store named in each entry's metadata. A missing key or a decryption/authentication failure is reported as a recipe error; encrypted imports do not fall back to plaintext or environment variables. Changing authenticated metadata to target a different store invalidates the envelope, so configure the destination store before import.

Generating Encrypted Secrets Locally

This module does not include a standalone CLI for encrypting recipe values. Run an Orchard instance locally and execute a Secrets deployment plan, or use ISecretEncryptionService from custom code in a configured tenant scope:

var info = new SecretInfo
{
    Name = "SmtpPassword",
    Store = "Database",
    Type = nameof(TextSecret),
};
var encrypted = await _secretEncryptionService.EncryptAsync(
    new TextSecret { Text = password },
    "Deployment.EncryptionKey",
    info);

The local instance needs the destination's public key registered as Deployment.EncryptionKey. _secretEncryptionService is the tenant's injected ISecretEncryptionService; password comes from a secure input, not a source-code literal. Copy the returned Version, EncryptedKey, EncryptedData, IV, and Tag into the recipe entry shown above, preserving info.Name as its key and the same store, type, description, and expiration in SecretInfo.

An external encryption tool must reproduce the provider's serialization, versioned envelope, RSA-OAEP-SHA256 key wrapping, and AES-GCM authenticated metadata exactly. A generic RSA or AES command does not by itself produce an importable recipe.

Important Requirements: - The encryption key must exist on the target with the same name - For RsaKeySecret: IncludesPrivateKey must be true - For X509Secret: The certificate must have a private key, from its certificate store or from the PEM-encoded private key of the secret

Multi-Tenant Migration Example

Scenario: Clone secrets from TenantA to TenantB

  1. In TenantB's scope, generate and save the RSA key pair as Deployment.EncryptionKey using the destination provisioning example above.
  2. Copy only its public key to TenantA and save a public-key-only Deployment.EncryptionKey in TenantA's scope. Keep the private key in TenantB.
  3. In TenantA, execute a deployment plan with a Secrets step selecting Deployment.EncryptionKey. Download the generated recipe, which excludes the selected key secret.
  4. In TenantB, ensure the named destination stores and secret type providers are available, then import the recipe. TenantB resolves its local private key, verifies the authenticated entries, and saves the decrypted secrets.

No request to TenantB is made during export. Do not attempt to provision an RSA key using an array recipe's text Value field: that field creates a TextSecret, not an RsaKeySecret.

Security Best Practices

  1. Protect the encryption key: The encryption key itself should be treated as highly sensitive
  2. Use different keys per environment: Don't share deployment keys between production and non-production
  3. Rotate keys periodically: Create new deployment keys and re-encrypt exports regularly
  4. Delete exported files: Don't leave encrypted exports in accessible locations
  5. Audit key usage: Log when deployment keys are used for export/import
  6. Consider X509 for compliance: Use CA-issued certificates for audit trails

Secret Types

The module supports three built-in secret types, each designed for specific use cases:

Choosing Between RsaKeySecret and X509Secret

Both RsaKeySecret and X509Secret can be used for cryptographic operations, but they serve different deployment models:

Aspect RsaKeySecret X509Secret (certificate store) X509Secret (PEM-encoded certificate)
Storage Key material stored in the secret store (encrypted) Reference to OS certificate store Certificate and private key stored in the secret store (encrypted)
Portability ✅ Travels with database backup ❌ Cert must exist on each machine ✅ Travels with database backup
Container-friendly ✅ Works without mounting certs ❌ Requires cert pre-installed ✅ Works without mounting certs
Key generation ✅ Generate in Admin UI ❌ Create cert externally ❌ Create cert externally
Cross-platform ✅ Works identically everywhere ⚠️ Enumeration varies by OS ✅ Works identically everywhere
Certificate metadata ❌ No issuer, expiry, subject ✅ Full X.509 metadata ✅ Full X.509 metadata
CA-issued certs ❌ Not applicable ✅ Works with CA certs ✅ Works with CA certs
Security model Key stored encrypted in the secret store Key never leaves OS secure store Key stored encrypted in the secret store

When to use RsaKeySecret:

  • OpenID Connect signing keys that must persist across container restarts
  • JWT signing for APIs (self-contained, portable)
  • Multi-server deployments where keys should auto-sync via database
  • Development/testing without certificate infrastructure

When to use X509Secret:

  • CA-issued certificates (SSL/TLS, client authentication)
  • Azure App Service certificates uploaded via portal
  • Enterprise PKI where certificates are managed by IT
  • Scenarios requiring certificate metadata (issuer validation, expiry checking)

Prefer a PEM-encoded certificate when the certificate store is not convenient, which is typically the case on Linux, in containers, and on shared hosting.

TextSecret

The most common secret type for storing string values like passwords, API keys, and connection strings.

public class TextSecret : ISecret
{
    public string Text { get; set; }
}

Use cases:

  • SMTP passwords
  • API keys (Stripe, SendGrid, etc.)
  • Database connection strings
  • OAuth client secrets

Example:

// Store an API key
var secret = new TextSecret { Text = "sk_live_abc123..." };
await _secretManager.SaveSecretAsync("Stripe.SecretKey", secret);

// Retrieve and use
var retrieved = await _secretManager.GetSecretAsync<TextSecret>("Stripe.SecretKey");
var apiKey = retrieved?.Text;

RsaKeySecret

For storing RSA cryptographic keys directly in the secrets store. The key material is encrypted and stored in the database, making it portable across deployments.

public class RsaKeySecret : ISecret
{
    public string PublicKey { get; set; }      // Base64-encoded RSA public key
    public string PrivateKey { get; set; }     // Base64-encoded RSA private key
    public bool IncludesPrivateKey { get; set; }
    public int KeySize { get; set; } = 2048;
}

Use cases:

  • OpenID Connect signing keys (addresses issues #7137, #13205)
  • JWT token signing/validation
  • Data encryption/decryption
  • Digital signatures
  • Any scenario requiring portable RSA keys

Benefits over X509Secret:

  • Key travels with database backup/restore
  • Works in containers without cert mounting
  • Can generate keys directly in Admin UI
  • Works identically on Windows/Linux/macOS
  • Automatically shared across servers via database

Example:

// Generate and store a new RSA key pair
using var rsa = RSA.Create(2048);
var secret = new RsaKeySecret
{
    PublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey()),
    PrivateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey()),
    IncludesPrivateKey = true,
    KeySize = 2048
};
await _secretManager.SaveSecretAsync("OpenId.SigningKey", secret);

// Retrieve and use for signing
var retrieved = await _secretManager.GetSecretAsync<RsaKeySecret>("OpenId.SigningKey");
using var signingKey = RSA.Create();
signingKey.ImportRSAPrivateKey(Convert.FromBase64String(retrieved.PrivateKey), out _);

X509Secret

For X.509 certificates. Its Source defines where the certificate is loaded from:

  • X509SecretSource.Store, the default: the secret references a certificate of the operating system's certificate store. It stores only the certificate reference (thumbprint, location, store name), the actual certificate remains in the OS certificate store.
  • X509SecretSource.Pem: the secret contains the certificate material itself, the PEM-encoded certificate and, optionally, its PEM-encoded private key. It doesn't depend on a certificate store, so it works the same way on every platform.
public class X509Secret : ISecret
{
    public X509SecretSource Source { get; set; }      // Store or Pem

    public StoreLocation StoreLocation { get; set; }  // CurrentUser or LocalMachine
    public StoreName StoreName { get; set; }          // My, Root, etc.
    public string Thumbprint { get; set; }            // Certificate thumbprint

    public string CertificatePem { get; set; }        // PEM-encoded certificate, optionally followed by its chain
    public string PrivateKeyPem { get; set; }         // Unencrypted PEM-encoded private key, optional

    public static X509Secret FromPem(string certificatePem, string privateKeyPem = null);

    public X509Certificate2 GetCertificate();         // Loads cert from the OS store or the PEM-encoded material
}

Use cases:

  • CA-issued SSL/TLS certificates
  • Code signing certificates
  • Azure App Service certificates (uploaded via portal)
  • Client authentication certificates
  • Enterprise PKI scenarios
  • Any certificate managed by IT infrastructure

How it works with a certificate store:

  1. Certificate is installed in OS certificate store (manually, via Azure, or via deployment)
  2. X509Secret stores the thumbprint and store location as a "binding"
  3. At runtime, GetCertificate() loads the actual certificate from the OS store

How it works with a PEM-encoded certificate:

  1. The certificate and its private key are pasted in the secret editor, with the PEM-encoded certificate source, or provided to X509Secret.FromPem(). When the certificate also contains the private key, the private key is stored separately.
  2. The secret store keeps them encrypted, like any other secret value. The private key is never displayed in the admin: leave it empty when editing the secret to keep the current one.
  3. At runtime, GetCertificate() creates the certificate with X509Certificate2.CreateFromPem(). The private key is optional, but required to sign or decrypt data. It must be unencrypted, in the PKCS#8 (PRIVATE KEY), RSA (RSA PRIVATE KEY) or EC (EC PRIVATE KEY) format, and match the certificate.

Cross-platform notes for certificate stores:

  • Windows: Full access to CurrentUser and LocalMachine stores; Admin UI shows available certs
  • Linux: Limited to CurrentUser store (~/.dotnet/corefx/cryptography); Admin UI may be empty
  • macOS: Keychain access; may require permissions for LocalMachine

Example:

// Reference a certificate by thumbprint
var secret = new X509Secret
{
    StoreLocation = StoreLocation.LocalMachine,
    StoreName = StoreName.My,
    Thumbprint = "ABC123DEF456..."
};
await _secretManager.SaveSecretAsync("Ssl.Certificate", secret);

// Retrieve and use the certificate
var retrieved = await _secretManager.GetSecretAsync<X509Secret>("Ssl.Certificate");
var certificate = retrieved?.GetCertificate();
if (certificate != null)
{
    // certificate is an X509Certificate2 instance
    // Use for SSL, signing, encryption, etc.
}

// Store a PEM-encoded certificate and its private key
var pemSecret = X509Secret.FromPem(
    await File.ReadAllTextAsync("signing-certificate.pem"),
    await File.ReadAllTextAsync("signing-certificate.key"));
await _secretManager.SaveSecretAsync("OpenId.SigningCertificate", pemSecret);

Adding Secret Support to Your Own Credentials

A module that stores a password, an API key, a connection string, or any other credential, in its settings or elsewhere, can let users keep it in the Secrets module, without depending on it. The steps below use site settings; see Credentials Stored Outside Site Settings for content parts and other documents. The OrchardCore.Secrets.Abstractions package provides everything needed:

Piece Purpose
SecretInputViewModel The editor model of the credential.
<secret-input> tag helper Renders the editor of the credential.
SecretInputViewModel.Create() and UpdateAsync() Read the stored values into the editor, and validate and apply the posted ones.
IServiceProvider.GetSecretValueAsync() Reads the clear value at runtime.
DisplayDriver<SecretMigration> (optional) Lists the credential on the Migrate Secrets screen.

What the user sees

  • Without the Secrets feature, the editor is a password input. The value is protected with Data Protection and kept in the settings, and an empty value keeps the current one. This is how credentials were stored before the Secrets module, so existing values keep working.
  • With the Secrets feature, the user chooses where the value is kept:
    • User-specified value, the default, keeps the value entered in the settings, as above.
    • Use a secret selects a TextSecret of the Secrets module. New secret opens the secret editor in a new tab, with a suggested name filled in. Once the secret is saved, the reload button refreshes the list without reloading the page, and selects the suggested secret. The value kept in the settings is removed when the settings are saved with a secret.

A value already kept in the settings can be moved to a secret without being entered again, from the Migrate Secrets screen.

Step 1: Reference the abstractions

Add a reference to OrchardCore.Secrets.Abstractions. Don't add a dependency on the OrchardCore.Secrets feature in the manifest: the editor and the runtime helper detect whether it is enabled.

Step 2: Store the protected value and the secret name

Keep the protected value, as before, and add a property that holds the name of the secret. The secret takes precedence when it is set.

public class MyServiceSettings
{
    // The API key, protected with Data Protection.
    public string ApiKey { get; set; }

    // The name of the secret containing the API key, which takes precedence over ApiKey.
    public string ApiKeySecretName { get; set; }
}

Use a constant for the Data Protection purpose, and a suggested secret name:

public static class MyServiceConstants
{
    public const string ProtectorName = "MyService";

    public const string ApiKeySecretName = "MyService.ApiKey";
}

Warning

Keep the purpose of the protector unchanged. Values protected with another purpose can't be decrypted, and can't be moved to secrets.

Step 3: Use SecretInputViewModel in the editor model

public class MyServiceSettingsViewModel
{
    public SecretInputViewModel ApiKey { get; set; } = new();
}

Step 4: Read and apply the credential in the display driver

SecretInputViewModel.Create() builds the editor model from the stored values. UpdateAsync() validates the posted model, adds errors to the model state, and returns the values to store, protecting a new value with the given protector. Only store them when the result succeeded.

public sealed class MyServiceSettingsDisplayDriver : SiteDisplayDriver<MyServiceSettings>
{
    private readonly IDataProtectionProvider _dataProtectionProvider;
    private readonly IServiceProvider _serviceProvider;

    public MyServiceSettingsDisplayDriver(
        IDataProtectionProvider dataProtectionProvider,
        IServiceProvider serviceProvider)
    {
        _dataProtectionProvider = dataProtectionProvider;
        _serviceProvider = serviceProvider;
    }

    protected override string SettingsGroupId => "MyService";

    public override IDisplayResult Edit(ISite site, MyServiceSettings settings, BuildEditorContext context)
        => Initialize<MyServiceSettingsViewModel>("MyServiceSettings_Edit", model =>
        {
            model.ApiKey = SecretInputViewModel.Create(settings.ApiKey, settings.ApiKeySecretName);
        }).Location("Content:5")
        .OnGroup(SettingsGroupId);

    public override async Task<IDisplayResult> UpdateAsync(ISite site, MyServiceSettings settings, UpdateEditorContext context)
    {
        var model = new MyServiceSettingsViewModel();
        await context.Updater.TryUpdateModelAsync(model, Prefix);

        var apiKey = await model.ApiKey.UpdateAsync(new SecretInputUpdateContext(
            _serviceProvider,
            _dataProtectionProvider.CreateProtector(MyServiceConstants.ProtectorName),
            context.Updater.ModelState,
            $"{Prefix}.{nameof(model.ApiKey)}")
        {
            ProtectedValue = settings.ApiKey,
            SecretName = settings.ApiKeySecretName,
        });

        if (apiKey.Succeeded)
        {
            settings.ApiKey = apiKey.ProtectedValue;
            settings.ApiKeySecretName = apiKey.SecretName;
        }

        return await EditAsync(site, settings, context);
    }
}

The last argument of SecretInputUpdateContext must be the full name of the edited property, so that the errors are shown next to it.

Step 5: Render the editor

Add the tag helper to Views/_ViewImports.cshtml:

@addTagHelper *, OrchardCore.Secrets.Abstractions

Then render the credential in a standard row. The secret-name attribute is the name suggested when the user creates a secret for this credential, and placeholder is optional:

<div class="ocat-wrapper" asp-validation-class-for="ApiKey">
    <label asp-for="ApiKey" class="ocat-label">@T["API key"]</label>
    <div class="ocat-end">
        <secret-input asp-for="ApiKey" secret-name="@MyServiceConstants.ApiKeySecretName" />
        <span class="hint">@T["The API key of the service."]</span>
    </div>
</div>

The first control of the editor gets the id of the property, so <label asp-for> targets it.

Step 6: Read the clear value at runtime

GetSecretValueAsync() reads the referenced secret when the Secrets feature is enabled, and otherwise decrypts the protected value. It returns null when no value is available, and logs why, without logging values.

var apiKey = await _serviceProvider.GetSecretValueAsync(
    settings.ApiKeySecretName,
    settings.ApiKey,
    _dataProtectionProvider.CreateProtector(MyServiceConstants.ProtectorName),
    _logger);

When the value is used to build options that are cached, for instance in an IConfigureOptions<T>, release the tenant or signal the options change when the settings are saved, as the settings already did.

Step 7: List the credential on the Migrate Secrets screen (optional)

To let users move a value kept in the settings to a secret without entering it again, add a display driver of SecretMigration. Register it only when the Secrets feature is enabled. Its editor renders a SecretMigrationItem_Edit shape when a protected value is kept and no secret is referenced, and its update moves the selected credential with MoveToSecretAsync().

Several drivers edit the same SecretMigration, so each one must bind its own fields: override BuildPrefix() to append a segment to the prefix.

public sealed class MyServiceSecretMigrationDisplayDriver : DisplayDriver<SecretMigration>
{
    private readonly ISiteService _siteService;
    private readonly ISecretManager _secretManager;
    private readonly IDataProtectionProvider _dataProtectionProvider;

    internal readonly IStringLocalizer S;

    public MyServiceSecretMigrationDisplayDriver(
        ISiteService siteService,
        ISecretManager secretManager,
        IDataProtectionProvider dataProtectionProvider,
        IStringLocalizer<MyServiceSecretMigrationDisplayDriver> stringLocalizer)
    {
        _siteService = siteService;
        _secretManager = secretManager;
        _dataProtectionProvider = dataProtectionProvider;
        S = stringLocalizer;
    }

    protected override void BuildPrefix(SecretMigration model, string htmlFieldPrefix)
    {
        base.BuildPrefix(model, htmlFieldPrefix);
        Prefix += ".MyService";
    }

    public override async Task<IDisplayResult> EditAsync(SecretMigration migration, BuildEditorContext context)
    {
        var settings = await _siteService.GetSettingsAsync<MyServiceSettings>();

        if (!CanMigrate(settings))
        {
            return null;
        }

        return Initialize<SecretMigrationItemViewModel>("SecretMigrationItem_Edit", model =>
        {
            model.Group = S["My service"];
            model.DisplayName = S["API key"];
            model.SecretName = MyServiceConstants.ApiKeySecretName;
        }).Location("Content");
    }

    public override async Task<IDisplayResult> UpdateAsync(SecretMigration migration, UpdateEditorContext context)
    {
        var site = await _siteService.LoadSiteSettingsAsync();
        var settings = site.GetOrCreate<MyServiceSettings>();

        if (!CanMigrate(settings))
        {
            return null;
        }

        var model = new SecretMigrationItemViewModel();
        await context.Updater.TryUpdateModelAsync(model, Prefix);

        if (model.Migrate)
        {
            await migration.MoveToSecretAsync(
                _secretManager,
                _dataProtectionProvider.CreateProtector(MyServiceConstants.ProtectorName),
                settings.ApiKey,
                model.SecretName,
                S["My service: API key"],
                async secretName =>
                {
                    settings.ApiKeySecretName = secretName;
                    settings.ApiKey = null;

                    site.Put(settings);
                    await _siteService.UpdateSiteSettingsAsync(site);
                });
        }

        return await EditAsync(migration, context);
    }

    private static bool CanMigrate(MyServiceSettings settings)
        => !string.IsNullOrWhiteSpace(settings.ApiKey) && string.IsNullOrWhiteSpace(settings.ApiKeySecretName);
}

[RequireFeatures("OrchardCore.Secrets")]
public sealed class SecretsStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
        => services.AddDisplayDriver<SecretMigration, MyServiceSecretMigrationDisplayDriver>();
}

MoveToSecretAsync() saves the secret right away, but only calls the last argument, which makes the settings reference the secret, once every driver has saved its secrets: a secret store can commit a secret in its own scope, which must not wait on settings that the same request already changed. So don't change the settings anywhere else in the driver. It never overwrites an existing secret, and records a failed move, for instance when the value can't be decrypted, without calling it. Also check the permission that guards your settings before listing or moving the credential.

Credentials Stored Outside Site Settings

The same steps apply to a credential stored anywhere else, for instance in a content part, a custom document, or a workflow activity: keep the protected value and the secret name side by side, edit them with a SecretInputViewModel, and read them with GetSecretValueAsync(). Only the driver and the persistence change.

For example, a WebhookPart that keeps the key used to sign the requests sent by each webhook content item:

public sealed class WebhookPart : ContentPart
{
    public string Url { get; set; }

    // The signing key, protected with Data Protection.
    public string SigningKey { get; set; }

    // The name of the secret containing the signing key, which takes precedence over SigningKey.
    public string SigningKeySecretName { get; set; }
}

public class WebhookPartViewModel
{
    public string Url { get; set; }

    public SecretInputViewModel SigningKey { get; set; } = new();

    [BindNever]
    public string SuggestedSecretName { get; set; }
}

The content part driver works like the site settings driver. The part is saved with its content item, so the driver only updates its properties:

public sealed class WebhookPartDisplayDriver : ContentPartDisplayDriver<WebhookPart>
{
    // The purpose must never change, or the stored keys can't be decrypted anymore.
    public const string ProtectorName = "Webhooks.SigningKey";

    private readonly IDataProtectionProvider _dataProtectionProvider;
    private readonly IServiceProvider _serviceProvider;

    public WebhookPartDisplayDriver(
        IDataProtectionProvider dataProtectionProvider,
        IServiceProvider serviceProvider)
    {
        _dataProtectionProvider = dataProtectionProvider;
        _serviceProvider = serviceProvider;
    }

    public override IDisplayResult Edit(WebhookPart part, BuildPartEditorContext context)
        => Initialize<WebhookPartViewModel>(GetEditorShapeType(context), model =>
        {
            model.Url = part.Url;
            model.SigningKey = SecretInputViewModel.Create(part.SigningKey, part.SigningKeySecretName);

            // Each webhook can get its own secret.
            model.SuggestedSecretName = $"Webhooks.{part.ContentItem.ContentItemId}.SigningKey";
        });

    public override async Task<IDisplayResult> UpdateAsync(WebhookPart part, UpdatePartEditorContext context)
    {
        var model = new WebhookPartViewModel();
        await context.Updater.TryUpdateModelAsync(model, Prefix);

        var signingKey = await model.SigningKey.UpdateAsync(new SecretInputUpdateContext(
            _serviceProvider,
            _dataProtectionProvider.CreateProtector(ProtectorName),
            context.Updater.ModelState,
            $"{Prefix}.{nameof(model.SigningKey)}")
        {
            ProtectedValue = part.SigningKey,
            SecretName = part.SigningKeySecretName,
        });

        if (signingKey.Succeeded)
        {
            part.SigningKey = signingKey.ProtectedValue;
            part.SigningKeySecretName = signingKey.SecretName;
        }

        part.Url = model.Url;

        return Edit(part, context);
    }
}

The editor view, WebhookPart.Edit.cshtml, renders the input like any other field, with the suggested name computed by the driver:

@model WebhookPartViewModel

<div class="ocat-wrapper" asp-validation-class-for="SigningKey">
    <label asp-for="SigningKey" class="ocat-label">@T["Signing key"]</label>
    <div class="ocat-end">
        <secret-input asp-for="SigningKey" secret-name="@Model.SuggestedSecretName" />
        <span class="hint">@T["The key used to sign the requests sent to the webhook."]</span>
    </div>
</div>

At runtime, read the key from the part of the content item being processed:

var part = contentItem.As<WebhookPart>();

var signingKey = await _serviceProvider.GetSecretValueAsync(
    part.SigningKeySecretName,
    part.SigningKey,
    _dataProtectionProvider.CreateProtector(WebhookPartDisplayDriver.ProtectorName),
    _logger);

A credential stored in a custom document, for instance one managed by an IDocumentManager<TDocument>, follows the same pattern: load the document for update, apply the values returned by UpdateAsync() to it, and save it with the document manager.

Credentials stored per item can be numerous, so think twice before listing them on the Migrate Secrets screen. Users can select a secret in each item instead. If you do contribute them, list a bounded number of items in the SecretMigration driver, save each moved item with its own service, such as IContentManager.UpdateAsync(), and give each item its own secret name.

Using the SelectSecret ViewComponent

When a setting must always reference a secret, for instance an RSA key, you can use the SelectSecret ViewComponent to provide a dropdown of available secrets:

@await Component.InvokeAsync("SelectSecret", new {
    secretTypes = new[] { "TextSecret" }, // Filter by type (optional)
    selectedSecret = Model.SecretName,
    htmlId = "SecretName",
    htmlName = "SecretName",
    required = true
})

This renders a dropdown populated with all secrets of the specified type. As the view component belongs to the Secrets module, the feature that renders it must depend on OrchardCore.Secrets.

Use Html.IdFor and Html.NameFor when the editor has a binding prefix. The optional cssClass parameter adds a CSS class to the select element for client-side behavior.

Permissions

Permission Description
ManageSecrets Allows managing (create, edit, delete) secrets
ViewSecrets Allows viewing the list of secrets (but not their values)

Implementing a Custom Secret Store

You can implement a custom secret store by implementing ISecretStore:

public class MyCustomSecretStore : ISecretStore
{
    public string Name => "MyCustomStore";
    public bool IsReadOnly => false;

    public Task<T> GetSecretAsync<T>(string name) where T : class, ISecret
    {
        // Implementation
    }

    public Task SaveSecretAsync<T>(string name, T secret, SecretSaveOptions options = null) where T : class, ISecret
    {
        // Implementation
    }

    public Task RemoveSecretAsync(string name)
    {
        // Implementation
    }

    public Task<IEnumerable<SecretInfo>> GetSecretInfosAsync()
    {
        // Implementation
    }
}

Register your store in Startup.cs:

public override void ConfigureServices(IServiceCollection services)
{
    services.AddSecretStore<MyCustomSecretStore>();
}

The secret manager, encryption service, stores, and type providers are registered as singletons within each tenant's shell. This allows singleton options monitors to resolve credentials. Custom stores and providers must support concurrent calls and must not depend directly on scoped services.

Potential custom store implementations:

  • HashiCorp Vault
  • AWS Secrets Manager
  • Google Cloud Secret Manager
  • CyberArk
  • 1Password Connect

Security Considerations

How Secrets Are Encrypted

The Secrets module uses ASP.NET Core Data Protection to encrypt all secrets before storing them in the database. Here's how it works:

  1. Encryption Process: When you save a secret, it's serialized to JSON and then encrypted using the Data Protection API
  2. Key Management: Data Protection automatically generates and manages encryption keys
  3. Storage: Encrypted secrets are stored in the SecretsDocument in the database

The encryption is transparent - you work with plain text values in the Admin UI and code, but the actual stored data is always encrypted.

Configuring Data Protection Keys (Important for Production)

By default, Data Protection stores keys in a local folder, which works for development but will cause problems in production because:

  • Keys are lost when containers restart
  • Multiple server instances can't share keys
  • Secrets encrypted on one server can't be decrypted on another

For Azure App Service / Azure Deployments

Use Azure Blob Storage and Azure Key Vault for key persistence:

// In Program.cs or Startup.cs
services.AddDataProtection()
    .PersistKeysToAzureBlobStorage(new Uri("https://yourstorage.blob.core.windows.net/dataprotection/keys.xml"))
    .ProtectKeysWithAzureKeyVault(new Uri("https://yourvault.vault.azure.net/keys/DataProtectionKey"), new ManagedIdentityCredential(ManagedIdentityId.SystemAssigned));

Or use the OrchardCore.DataProtection.Azure module:

{
  "OrchardCore": {
    "OrchardCore_DataProtection_Azure": {
      "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...;EndpointSuffix=core.windows.net",
      "ContainerName": "dataprotection",
      "BlobName": "keys.xml",
      "CreateContainer": true
    }
  }
}

For Docker / Kubernetes

Mount a persistent volume for keys:

services.AddDataProtection()
    .PersistKeysToFileSystem(new DirectoryInfo("/app/keys"))
    .SetApplicationName("OrchardCore");

Or use Redis:

services.AddDataProtection()
    .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

For Multi-Server Deployments

All servers must share the same Data Protection keys. Options:

  1. Azure Blob Storage (recommended for Azure)
  2. Redis (recommended for Kubernetes)
  3. Database (using PersistKeysToDbContext)
  4. Shared file system (NFS, Azure Files)

Encryption at Rest

Encryption at rest means data is encrypted while it is stored somewhere, rather than while it is moving between systems. Protecting data as it moves between systems is called encryption in transit.

All secrets stored in the database are encrypted using ASP.NET Core Data Protection. This means:

  • Secrets are encrypted before being written to the database
  • Encryption keys are managed by the Data Protection system
  • In production, configure Data Protection to persist keys securely (Azure Blob Storage, Redis, etc.)

Access Control

  • Only users with the ManageSecrets permission can create, edit, or delete secrets
  • The ViewSecrets permission allows viewing secret metadata (names, types) but not actual values
  • Secret values are never returned to the browser after creation (edit forms show empty password fields)

Deployment Security

  • Never include secret values directly in recipe files or deployment plans
  • Use environment variables to provide secret values during deployment
  • Deployment exports include only metadata (name, type, store) not actual values

Azure Key Vault Benefits

For production environments, consider Azure Key Vault for:

  • Hardware Security Module (HSM) backed key storage
  • Centralized access policies and audit logging
  • Automatic secret rotation capabilities
  • Managed Identity support (no credentials in configuration)

Best Practices

  1. Use descriptive names: Name secrets clearly (e.g., Smtp.Password, Stripe.LiveSecretKey)
  2. Separate by environment: Use different Azure Key Vaults for dev/staging/production
  3. Rotate regularly: Implement secret rotation policies
  4. Audit access: Enable logging to track who accesses secrets
  5. Principle of least privilege: Grant only necessary permissions to users and services
  6. Configure Data Protection: Always configure key persistence for production deployments

This module addresses several long-standing issues in Orchard Core:

Issue Problem How Secrets Module Helps
#7137 "Keyset does not exist" crash with OpenID certificates Store signing keys as RsaKeySecret instead of file-based certificates
#13205 External storage needed for OpenID certificates Use Azure Key Vault or database storage for certificates
#5558 Deployment steps can't handle secrets Secrets recipe step imports from environment variables
#3259 Certificate selection in Azure App Service X509Secret can reference certificates from the certificate store

Migration Guide

Credentials kept in the settings of a feature keep working after an upgrade, with or without the Secrets feature. Move them to secrets on demand from the Migrate Secrets screen, or select a secret in each settings screen. A credential is only replaced after a successful Data Protection decryption and secret persistence; failures are reported and leave the settings unchanged, and encrypted payloads are never treated as plaintext. Preserve the original Data Protection key ring during upgrades.

Credentials supplied directly through configuration produce a LegacySecretConfiguration warning (event ID 8100) when their options are initialized. The warning identifies the tenant, integration, and current configuration key, but never includes the value. After moving credentials to secrets and removing the old configuration values, restart the application, activate each tenant, exercise its configured integrations, and check the logs again. Also audit configuration sources directly: options initialize lazily and overridden or unused configuration values may not produce warnings. See the 4.0 upgrade instructions for the affected keys, legacy aliases, and verification procedure.

From appsettings.json Passwords

If you're currently storing passwords in configuration:

Before:

{
  "OrchardCore": {
    "OrchardCore_Email_Smtp": {
      "Password": "my-smtp-password"
    }
  }
}

After:

  1. Enable the Secrets module
  2. In the SMTP settings, select Use a secret, click New secret to create the Smtp.Password secret in a new tab, reload the secrets, and save.
  3. Remove the password from configuration files

From Environment Variables

Environment variables are still useful for providing initial secret values during deployment, but the Secrets module provides a better runtime storage mechanism:

  1. Keep environment variables for deployment/setup
  2. Use the Secrets recipe step to import values during site setup
  3. After setup, secrets are stored encrypted in the database or Key Vault

Module Integrations

Built-in features can keep their credentials in the Secrets module, and an optional integration module covers the OpenID Connect server keys.

Credentials of Built-in Features

The following settings render their credential with the secret input, and contribute it to the Migrate Secrets screen. They don't depend on the Secrets feature.

Feature Credential Suggested secret name
SMTP email Password Smtp.Password
Azure email Connection string AzureEmail.ConnectionString
Twilio SMS Auth token Twilio.AuthToken
Azure SMS Connection string AzureSms.ConnectionString
Meta (Facebook) App secret Facebook.AppSecret
GitHub authentication Client secret GitHub.ClientSecret
Google authentication Client secret Google.ClientSecret
Microsoft Account authentication App secret MicrosoftAccount.AppSecret
X (Twitter) Consumer secret, access token secret Twitter.ConsumerSecret, Twitter.AccessTokenSecret
OpenID Connect client Client secret OpenIdClient.ClientSecret
Azure AI Search API key AzureAISearch.ApiKey

OpenID Connect Secrets (OrchardCore.OpenId.Secrets)

This optional feature is included in the OrchardCore.OpenId module and allows you to store OpenID Connect signing and encryption keys as secrets instead of using auto-generated certificates. It must be enabled explicitly; enabling the OpenID Connect server and Secrets features alone does not activate it. No separate OpenID Connect Secrets package is required.

Prerequisites:

  • OrchardCore.OpenId.Server - OpenID Connect server
  • OrchardCore.Secrets - Core secrets module

Setup:

  1. Enable the OrchardCore.OpenId.Secrets feature
  2. Create an RsaKeySecret for signing (with private key) or an X509Secret referencing a certificate
  3. Optionally create a separate secret for encryption
  4. Go to Security → OpenID Connect → Server Settings
  5. In the RSA Keys from Secrets card, select your secrets

Automatic Migration:

When you enable OrchardCore.OpenId.Secrets, existing X.509 certificate configurations from OpenID Server settings are automatically migrated:

  • If you previously configured signing/encryption certificates via the OpenID Server settings UI
  • The module creates X509Secret entries referencing those certificates
  • The OpenIdSecretSettings is updated to point to the new secrets
  • Your existing certificate configurations continue to work seamlessly

Secret Type Fallback:

The module supports both RsaKeySecret and X509Secret for signing/encryption keys:

  1. First, it tries to load the configured secret as an RsaKeySecret (portable, recommended)
  2. If not found, it falls back to X509Secret (certificate store reference)
  3. This allows gradual migration from certificate-based to RSA key-based secrets

Benefits:

  • Keys persist across deployments and container restarts
  • Can share signing keys across multiple instances
  • Keys stored in Azure Key Vault for HSM-backed security
  • Addresses issues #7137 and #13205

Generating RSA Keys:

using var rsa = RSA.Create(2048);
var secret = new RsaKeySecret
{
    PublicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey()),
    PrivateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey()),
    IncludesPrivateKey = true
};
await _secretManager.SaveSecretAsync("OpenId.SigningKey", secret);

Or use the Admin UI to create an RSA secret with auto-generated keys.