Dela via


Get a secret from Azure Key Vault with JavaScript

Create the SecretClient with the appropriate programmatic authentication credentials, then use the client to get a secret from Azure Key Vault.

Get current version of secret

To get a secret in Azure Key Vault, use the getSecret method of the SecretClient class.

const name = 'mySecret';

const { name, properties, value } = await client.getSecret(secretName);

This method returns the KeyVaultSecret object.

Get any version of secret

To get a specific version of a secret in Azure Key Vault, use the GetSecretOptions object when you call the getSecret method of the SecretClient class. This method returns the KeyVaultSecret object.

const name = 'mySecret';
const options = {
    version: 'd9f2f96f120d4537ba7d82fecd913043'
};
 
const { name, properties, value } = await client.getSecret(secretName, options);

This method returns the KeyVaultSecret object.

Get all versions of a secret

To get all versions of a secret in Azure Key Vault, use the listPropertiesOfSecretVersions method of the SecretClient Class to get an iterable list of secret's version's properties. This returns a SecretProperties object, which doesn't include the version's value. If you want the version's value, use the version returned in the property to get the secret's value with the getSecret method.

Metod Returns value Returns properties
getSecret Ja Ja
listPropertiesOfSecretVersions Nej Ja
const versions = [];

for await (const secretProperties of client.listPropertiesOfSecretVersions(
secretName
)) {
    const { value } = await client.getSecret(secretName, {
        version: secretProperties?.version,
    });

    versions.push({
        name: secretName,
        version: secretProperties?.version,
        value: value,
        createdOn: secretProperties?.createdOn,
    });
}

Get disabled secret

Use the following table to understand what you can do with a disabled secret.

Tillåtet Tillåts inte
Enable secret
Update properties
Get value

Nästa steg