Вывод списка или поиска секрета в Azure Key Vault с помощью JavaScript

Создайте SecretClient с соответствующими учетными данными программатической проверки подлинности, а затем используйте клиент для поиска секрета из Azure Key Vault.

Все методы списка возвращают итерируемый объект. Вы можете получить все элементы списка или вызвать в цепочке метод byPage, чтобы перебирать элементы по одной странице за раз.

После получения свойства секрета можно использовать метод getSecret , чтобы получить значение секрета.

Перечисление всех секретов

Чтобы перечислить все секреты в Azure Key Vault, используйте метод listPropertiesOfSecrets для получения свойств текущего секрета.

for await (const secretProperties of client.listPropertiesOfSecrets()){

  // do something with properties
  console.log(`Secret name: ${secretProperties.name}`);

}

Этот метод возвращает объект SecretProperties .

Перечисление всех секретов по странице

Чтобы перечислить все секреты в Azure Key Vault, используйте метод listPropertiesOfSecrets для получения свойств секрета на странице за раз, задав объект PageSettings.

// 5 secrets per page
const maxResults = 5;
let pageCount = 1;
let itemCount=1;

// loop through all secrets
for await (const page of client.listPropertiesOfSecrets().byPage({ maxPageSize: maxResults })) {

  let itemOnPageCount = 1;

  // loop through each secret on page
  for (const secretProperties of page) {
    
    console.log(`Page:${pageCount++}, item:${itemOnPageCount++}:${secretProperties.name}`);
    
    itemCount++;
  }
}
console.log(`Total # of secrets:${itemCount}`);

Этот метод возвращает объект SecretProperties .

Вывести список всех версий секрета

Чтобы получить список всех версий секрета в Azure Key Vault, используйте метод listPropertiesOfSecretVersions.

for await (const secretProperties of client.listPropertiesOfSecretVersions(secretName)) {

  // do something with version's properties
  console.log(`Version created on: ${secretProperties.createdOn.toString()}`);
}

Этот метод возвращает объект SecretProperties .

Список удаленных секретов

Чтобы перечислить все удаленные секреты в Azure Key Vault, используйте метод listDeletedSecrets.

// 5 secrets per page
const maxResults = 5;
let pageCount = 1;
let itemCount=1;

// loop through all secrets
for await (const page of client.listDeletedSecrets().byPage({ maxPageSize: maxResults })) {

  let itemOnPageCount = 1;

  // loop through each secret on page
  for (const secretProperties of page) {
    
    console.log(`Page:${pageCount++}, item:${itemOnPageCount++}:${secretProperties.name}`);
    
    itemCount++;
  }
}
console.log(`Total # of secrets:${itemCount}`);

Объект secretProperties является объектом DeletedSecret .

Поиск секрета по свойству

Чтобы найти текущую (последнюю) версию секрета, которая соответствует имени или значению свойства, выполните цикл по всем секретам и сравните свойства. Следующий код JavaScript находит все включенные секреты.

Этот код использует следующий метод в цикле всех секретов:

  • listPropertiesOfSecrets() — возвращает объект свойств последней версии для каждого секрета

const secretsFound = [];

const propertyName = "enabled"
const propertyValue = false;

for await (const secretProperties of client.listPropertiesOfSecrets()){

  if(propertyName === 'tags'){
    if(JSON.stringify(secretProperties.tags) === JSON.stringify(propertyValue)){
      secretsFound.push( secretProperties.name )
    }
  } else {
    if(secretProperties[propertyName].toString() === propertyValue.toString()){
      secretsFound.push( secretProperties.name )
    }
  }
}

console.log(secretsFound)
/*
[
  'my-secret-1683734823721',
  'my-secret-1683735278751',
  'my-secret-1683735523489',
  'my-secret-1684172237551'
]
*/

Поиск версий по свойству

Чтобы найти все версии, соответствующие имени или значению свойства, выполните цикл по всем версиям секретов и сравните свойства.

Этот код использует следующие методы в вложенном цикле:

const secretsFound = [];

const propertyName = 'createdOn';
const propertyValue = 'Mon May 15 2023 20:52:37 GMT+0000 (Coordinated Universal Time)';

for await (const { name } of client.listPropertiesOfSecrets()){

  console.log(`Secret name: ${name}`);

  for await (const secretProperties of client.listPropertiesOfSecretVersions(name)) {
  
    console.log(`Secret version ${secretProperties.version}`);

    if(propertyName === 'tags'){
      if(JSON.stringify(secretProperties.tags) === JSON.stringify(propertyValue)){
        console.log(`Tags match`);
        secretsFound.push({ name: secretProperties.name, version: secretProperties.version });
      }
    } else {
      if(secretProperties[propertyName].toString() === propertyValue.toString()){
        console.log(`${propertyName} matches`);
        secretsFound.push({ name: secretProperties.name, version: secretProperties.version });
      }
    }
  }
}

console.log(secretsFound);
/*
[
  {
    name: 'my-secret-1684183956189',
    version: '93beaec3ff614be9a67cd2f4ef4d90c5'
  }
]
*/

Дальнейшие действия