诊断和排查 Azure Cosmos DB 未经授权异常Diagnose and troubleshoot Azure Cosmos DB unauthorized exception

HTTP 401:HTTP 请求中的 MAC 签名与计算出的签名不同。HTTP 401: The MAC signature found in the HTTP request is not the same as the computed signature. 如果收到以下 401 错误消息:“HTTP 请求中的 MAC 签名与计算出的签名不同。”If you received the following 401 error message: "The MAC signature found in the HTTP request is not the same as the computed signature." 此错误可能是由以下情况造成的。it can be caused by the following scenarios.

在较旧的 SDK 中,异常可能显示为无效的 json 异常,而不是正确的 401 未经授权异常。Older SDKs the exception can appear as an invalid json exception instead of the correct 401 unauthorized exception. 较新的 SDK 可以正确处理此情况,并提供有效的错误消息。Newer SDKs properly handle this scenario and give a valid error message.

疑难解答步骤Troubleshooting steps

以下列表包含未经授权异常的已知原因和解决方案。The following list contains known causes and solutions for unauthorized exception.

1.密钥未正确轮换是最常见的情况。1. Key was not properly rotated is the most common scenario.

密钥轮换之后不久就会出现 401 MAC 签名问题,但无需进行任何更改,它最终会停止。401 MAC signature is seen shortly after a key rotation and eventually stops without any changes.

解决方案:Solution:

密钥已轮换,且未遵循最佳做法The key was rotated and did not follow the best practices. 完成 Cosmos DB 帐户密钥轮换耗时几秒到几天不等,具体取决于 Cosmos DB 帐户大小。The Cosmos DB account key rotation can take anywhere from a few seconds to possibly days depending on the Cosmos DB account size.

2.密钥配置错误2. The key is misconfigured

401 MAC 签名问题持续出现并在使用该密钥的所有调用中发生401 MAC signature issue will be consistent and happens for all calls using that key

解决方案:Solution:

密钥在应用程序上配置错误,并且帐户使用了错误密钥或未复制整个密钥。The key is misconfigured on the application, and is using the wrong key for the account or entire key was not copied.

3.应用程序使用只读密钥进行写入操作3. The application is using the read-only keys for write operations

401 MAC 签名问题仅在创建或替换等写入操作中发生,但读取请求会成功。401 MAC signature issue is only occurring for write operations like create or replace, but read request succeed.

解决方案:Solution:

切换应用程序以使用读/写密钥,从而允许操作成功完成。Switch the application to use a read/write key to allow the operations to complete successfully.

4.创建容器时出现争用情况4. Race condition with create container

创建容器后不久看到 401 MAC 签名问题。401 MAC signature issue is seen shortly after a container creation. 此问题仅在容器创建完成后发生。This only occurs until the container creation is completed.

解决方案:Solution:

创建容器时出现争用状况。There is a race condition with container creation. 在完成容器创建之前,某个应用程序实例正在尝试访问容器。An application instance is trying to access the container before container creation is complete. 出现此争用条件的最常见情况是,应用程序正在运行就删除了容器,并重新创建了同名的容器。The most common scenario for this race condition is if the application is running, and the container is deleted and recreated with the same name. SDK 将尝试使用新容器,但由于容器创建仍在进行,因此无法获得密钥。The SDK will attempt to use the new container, but the container creation is still in progress so it does not have the keys.

后续步骤Next steps