我正在使用 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/