azure - 无法使用 azure JavaScript 函数和 Key Vault key 检索 cosmosDB 数据

标签 azure azure-functions azure-cosmosdb azure-keyvault azure-identity

我正在使用 Azure 函数(JavaScript/节点)从 CosmosDB 查询和检索数据。效果很好。但是,我尚未成功实现 key 保管库 secret 来存储 cosmosDB 的主 key 。我收到错误:

Executed 'Functions.getProjects' (Failed, Id=f319f320-af1c-4283-a8f4-43cc6becb3ca, 
Duration=1289ms)
[6/7/2021 4:37:44 AM] System.Private.CoreLib: Exception while executing function: 
Functions.getProjects. System.Private.CoreLib: Result: Failure
Exception: Error: Required Header authorization is missing. Ensure a valid Authorization token 
is passed.

我遵循了多个教程,了解如何在 Azure 中运行代码以及如何在 VS Code 中本地运行代码。为了在 Azure 中运行,我创建了 key 保管库并添加了 key 。我在我的函数上启用了系统分配的托管标识,以便它创建一个服务主体。然后,我在 Key Vault 中创建了一个访问策略,允许我的功能/服务主体 GET、LIST 功能。在 Azure 中测试该函数时,我遇到了与在本地测试时相同的错误。

我的代码:config.js - 为了安全起见,端点和 key 被隐藏

const config = {
  endpoint: "https://<mysiteonazure>.documents.azure.com:443/",
  key: 
  "myreallylongkeyhiddenforsecurity",
  databaseId: "projectsDB",
  containerId: "projects",
  partitionKey: { kind: "Hash", paths: ["/category"] },
};
module.exports = config;

我的代码:index.js

const config = require("../sharedCode/config");
const { CosmosClient } = require("@azure/cosmos");

const { DefaultAzureCredential } = require("@azure/identity");
const { SecretClient } = require("@azure/keyvault-secrets");

// this value is specified in local.settings.json file for local testing
const keyVaultName = process.env["KEY_VAULT_NAME"];

const keyVaultUri = `https://${keyVaultName}.vault.azure.net`;

// checks to see if local.settings.json has value first, indicates local
// second uses managed identity, indicating azure, since local.settings.js not uploaded
const credential = new DefaultAzureCredential();

const secretClient = new SecretClient(keyVaultUri, credential);

module.exports = async function (context, req) {
  
  const endpoint = config.endpoint;
  const key = await secretClient.getSecret("cosmosProjectKey");
  const keyx = key.value;

  const client = new CosmosClient({ endpoint, keyx });

  const database = client.database(config.databaseId);
  const container = database.container(config.containerId);

  const querySpec = {
    query: "SELECT * from c",
  };

  let myprojects = [];

  const { resources: items } = await container.items
    .query(querySpec)
    .fetchAll();

  items.forEach((item) => {
    myprojects.push(`${item.id} - ${item.project}`);
  });

  context.res = {
    // status: 200, /* Defaults to 200 */
    body: items,
  };
};

正如我所提到的,当我在配置文件中硬编码 key (不是最好的 JS 编码)时,我的代码可以工作。我删除了所有显示 key 值是从 key 保管库返回的注释。我还遗漏了我创建了另一个服务主体,我相信当我在本地运行该函数时尝试访问 key 保管库时会使用该主体。

非常感谢任何帮助。

最佳答案

请更改以下代码行:

const key = await secretClient.getSecret("cosmosProjectKey");
const keyx = key.value;

const secretKey = await secretClient.getSecret("cosmosProjectKey");
const key = secretKey.value;

并使用以下内容创建您的 CosmosClient

const client = new CosmosClient({ endpoint, key });

其他选项是像这样创建 CosmosClient:

const client = new CosmosClient({ endpoint, key: keyx });

关于azure - 无法使用 azure JavaScript 函数和 Key Vault key 检索 cosmosDB 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67866234/

相关文章:

azure - Documentdb 无效字符串文字标记

c# - 将函数定义作为 CI 流程的一部分导入 API 管理

azure - 有没有办法为 Azure 资源列表生成单个 MSI token ?

azure-cosmosdb - Database.ReadAsync() 有什么用?

c# - 使用 SeriLog 写入 Azure documentDb

azure - 获取 Azure Cosmos DB 集合中的所有分区键

Azure-一驱动器传输

c# - 身份验证 - 仅允许 HTTPS 方案

azure - 获取 webrole 所属部署的名称和位置

mongodb - Azure Function 与 Cosmos MongoDB 集成不保存