1

我正在使用 Azure 函数 (JavaScript/node) 从 CosmosDB 查询和检索数据。这很好用。但是,我还没有成功实现密钥库机密来存储 cosmosDB 的主密钥。我得到错误:

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 代码中本地运行代码需要做什么。为了在 Azure 中运行,我创建了我的密钥保管库并添加了机密。我在我的函数上启用了系统分配的托管标识,以便它创建一个服务主体。然后,我在密钥保管库中创建了一个访问策略,允许我的功能/服务主体 GET、LIST 功能。在 Azure 中测试函数时,我遇到与本地测试时相同的错误。

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

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,
  };
};

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

非常感谢任何帮助。

4

1 回答 1

2

请更改以下代码行:

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 });
于 2021-06-07T05:18:43.390 回答