Share via


使用 JavaScript 在 Azure Key Vault 中設定、更新及輪替秘密

使用適當的程式設計驗證認證來建立 SecretClient,然後使用用戶端在 Azure Key Vault 中設定、更新及輪替祕密。

設定秘密

若要在 Azure Key Vault 中設定秘密,請使用 SecretClient 類別的 setSecret 方法。

秘密值類型為字串。 初始值可以是可序列化為字串的任何值,例如 JSON 或 BASE64 編碼資料。 您必須在 Key Vault 中設定祕密之前序列化,並在從 Key Vault 取得祕密後還原序列化。

const name = 'mySecret';
const value = 'mySecretValue'; // or JSON.stringify({'key':'value'})

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

當您建立秘密時,KeyVaultSecret 回應包含 SecretProperties 物件,其中包含秘密的中繼資料,例如:

  • createdOn:建立祕密的 UTC 日期和時間。
  • id:秘密的完整 URL。
  • recoverableDays:祕密刪除後可以加以復原的天數。
  • recoveryLevel:包括 Purgeable'、'Recoverable+Purgeable'、'Recoverable'、'Recoverable+ProtectedSubscription' 等值。
  • updatedOn:上次更新祕密的 UTC 日期和時間。
  • version:秘密的版本。

使用屬性設定秘密

使用 SecretClient 類別的 setSecret 方法搭配 SetSecretOptions,以包含與祕密一起使用的選擇性參數,例如:

  • contentType:您對秘密內容類型的表示和認知。 使用的建議包括原生類型、您自己的自訂 TypeScript 類型或 MIME 類型。 此值可在 Azure 入口網站中看到。
  • enabled:預設為 true。
  • expiresOn:祕密到期的 UTC 日期和時間。
  • notBefore:在此之前無法使用祕密的 UTC 日期和時間。
  • tags:可用於與祕密建立關聯的自訂名稱/值組。
const name = 'mySecret';
const value = JSON.stringify({
    'mykey':'myvalue', 
    'myEndpoint':'https://myendpoint.com'
});
const secretOptions = {
    // example options
    contentType: 'application/json',
    tags: { 
        project: 'test-cluster', 
        owner: 'jmclane',
        team: 'devops'
    }
};

const { name, value, properties } = await client.setSecret(
    secretName,
    secretValue, 
    secretOptions
);

這個方法會傳回 KeyVaultSecret 物件。

更新祕密值

若要更新秘密值,請使用上一節所示的 setSecret 方法。 務必將新值作為字串傳遞,以及您想要從目前的祕密版本中保留的所有屬性。 未在對 setSecret 的其他呼叫中設定的任何目前屬性都會遺失。

這會產生新版本的祕密。 傳回的 SecretProperties 物件包含新版本識別碼。

更新祕密屬性

若要更新秘密屬性,請使用 SecretClient 類別的 updateSecretProperties 方法。 未在要求中指定的屬性會保留不變。 無法變更祕密本身的值。 此作業需要祕密/設定權限。

const name = 'mySecret';

// Update tags
const updatedTagName = 'existingTag';
const updatedTagValue = secret.properties.version.tags[updatedTagName] + ' additional information';

// Use version from existing secret
const version = secret.properties.version;

// Options to update
const secretOptions = {
    tags: {
        'newTag': 'newTagValue', // Set new tag
        'updatedTag': updatedTagValue // Update existing tag
    },
    enabled: false
}

// Update secret's properties - doesn't change secret name or value
const properties = await client.updateSecretProperties(
    secretName,
    secretVersion,
    secretOptions,
);

這個方法會傳回 SecretProperties 物件。

輪替祕密

若要輪替秘密,您必須為 SecretNearExpiry 事件建立事件方格事件訂用帳戶,並提供應使用事件觸發程序呼叫的輪替功能。 透過教學課程,針對使用下列驗證認證的資源,將資源秘密的輪替自動化

下一步