Get a key in Azure Key Vault with JavaScript

Create the KeyClient with the appropriate programmatic authentication credentials, then use the client to set, update, and rotate a key in Azure Key Vault.

Get key

You can get the latest version of a key or a specific version of a key with the getKey method. The version is within the properties of the KeyVaultKey object.

  • Get latest version: await client.getKey(name);
  • Get specific version: await client.getKey(name, { version });
// Azure client libraries
import { DefaultAzureCredential } from '@azure/identity';
import {
    KeyClient,
} from '@azure/keyvault-keys';

// Authenticate to Azure Key Vault
const credential = new DefaultAzureCredential();
const client = new KeyClient(
    `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
    credential
);

const name = `myRsaKey`;

// Get latest key
const latestKey = await client.getKey(name);
console.log(`${latestKey.name} version is ${latestKey.properties.version}`);

// Get previous key by version id
const keyPreviousVersionId = '2f2ec6d43db64d66ad8ffa12489acc8b';
const keyByVersion = await client.getKey(name, {
    version: keyPreviousVersionId
});
console.log(`Previous key version is ${keyByVersion.properties.version}`);

Get all versions of a key

To get all versions of a key in Azure Key Vault, use the listPropertiesOfKeyVersions method of the KeyClient Class to get an iterable list of key's version's properties. This returns a KeyProperties 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 key's value with the getKey method.

Method Returns value Returns properties
getKey Yes Yes
listPropertiesOfKeyVersions No Yes
// Azure client libraries
import { DefaultAzureCredential } from '@azure/identity';
import {
    KeyClient,
} from '@azure/keyvault-keys';

// Authenticate to Azure Key Vault
const credential = new DefaultAzureCredential();
const client = new KeyClient(
    `https://${process.env.AZURE_KEYVAULT_NAME}.vault.azure.net`,
    credential
);

const name = `myRsaKey`;

for await (const keyProperties of client.listPropertiesOfKeyVersions(name)) {
    const thisVersion = keyProperties.version;
    
    const { key } = await client.getKey(name, {
        version: thisVersion
    });

    // do something with version's key value
}

Get disabled key

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

Allowed Not allowed
Enable key
Update properties
Get value

Next steps