Azure Cosmos DB端点POST请求被禁止,如何授权远程代码创建数据库?
我正在学习Azure Cosmos DB(Core SQL)相关教程,尝试通过代码创建数据库。已从Cosmos DB账户的【设置】→【密钥】中正确复制了EndpointUri和Key,代码如下:
const string EndpointUri = "https://fergerg.azure.com:443/"; const string Key = "gvfvfdevgrvgre";
创建数据库的代码如下:
string databaseName = "demoDB_" + Guid.NewGuid().ToString().Substring(0, 5); client = new CosmosClient(EndpointUri, Key); database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
执行时返回403错误,具体异常信息如下:
Unhandled exception. System.AggregateException: One or more errors occurred. (Response status code does not indicate success: Forbidden (403); Substatus: 0; ActivityId: e10466; Reason: {"code":"Forbidden","message":"Operation 'POST' on resource 'dbs' is not allowed through Azure Cosmos DB endpoint. Please switch on such operations for your account, or perform this operation through Azure Resource Manager, Azure Portal, Azure CLI or Azure Powershell"\r\nActivityId: 14d3a978f6ee10466, Microsoft.Azure.Documents.Common/2.14.0"} RequestUri: https://sql-iknn-.documents.azure.com/dbs
即对端点documents.azure.com/dbs的POST请求被禁止。这是因为Azure Cosmos DB默认限制了通过SDK执行账户级管理操作,需按以下步骤授权:
开启SDK账户管理操作权限:
- 登录Azure门户,进入目标Cosmos DB账户
- 在左侧导航栏选择【设置】→【功能】
- 找到账户管理操作选项,勾选「允许通过SDK进行账户管理操作」
- 点击页面底部的【保存】按钮
确认密钥权限:
确保使用的是主密钥或次级密钥,只读密钥无法执行创建数据库这类写操作。检查网络访问规则:
若Cosmos DB账户配置了防火墙或虚拟网络限制,需将运行代码的主机IP添加到允许访问的IP列表中;测试环境可临时开启「允许从所有网络访问」,生产环境建议严格限定IP范围。
内容的提问来源于stack exchange,提问作者Serve Laurijssen

