保护对 Azure Cosmos DB 中数据的访问Secure access to data in Azure Cosmos DB

本文概述了如何保护对存储在 Azure Cosmos DB 中的数据的访问。This article provides an overview of securing access to data stored in Azure Cosmos DB.

Azure Cosmos DB 使用两种类型的密钥来验证用户身份并提供其数据和资源的访问权限。Azure Cosmos DB uses two types of keys to authenticate users and provide access to its data and resources.

密钥类型Key type 资源Resources
主密钥Master keys 用于管理资源:数据库帐户、数据库、用户和权限Used for administrative resources: database accounts, databases, users, and permissions
资源令牌Resource tokens 用于应用程序资源:容器、文档、附件、存储过程、触发器和 UDFUsed for application resources: containers, documents, attachments, stored procedures, triggers, and UDFs

主密钥Master keys

主密钥提供对数据库帐户的所有管理资源的访问权限。Master keys provide access to all the administrative resources for the database account. 主密钥:Master keys:

  • 提供对帐户、数据库、用户和权限的访问权限。Provide access to accounts, databases, users, and permissions.
  • 无法用于提供对容器和文档的精细访问权限。Cannot be used to provide granular access to containers and documents.
  • 在创建帐户过程中创建。Are created during the creation of an account.
  • 随时可重新生成。Can be regenerated at any time.

每个帐户包括两个主密钥:主要密钥和辅助密钥。Each account consists of two Master keys: a primary key and secondary key. 使用两个密钥的目的是为了能够重新生成或轮换密钥,从而可以持续访问帐户和数据。The purpose of dual keys is so that you can regenerate, or roll keys, providing continuous access to your account and data.

Azure Cosmos DB 帐户除了有两个主密钥以外,还有两个只读密钥。In addition to the two master keys for the Cosmos DB account, there are two read-only keys. 这些只读密钥只允许针对帐户执行读取操作。These read-only keys only allow read operations on the account. 只读密钥不提供对资源的读取权限。Read-only keys do not provide access to read permissions resources.

可以使用 Azure 门户检索和重新生成主要、辅助、只读和读写主密钥。Primary, secondary, read only, and read-write master keys can be retrieved and regenerated using the Azure portal. 有关说明,请参阅查看、复制和重新生成访问密钥For instructions, see View, copy, and regenerate access keys.

Azure 门户中的访问控制 (IAM) - 演示 NoSQL 数据库安全性

轮换主密钥的过程相当简单。The process of rotating your master key is simple. 导航到 Azure 门户并检索用户的辅助密钥,在应用程序中将主要密钥替换为该辅助密钥,并在 Azure 门户中轮换主要密钥即可。Navigate to the Azure portal to retrieve your secondary key, then replace your primary key with your secondary key in your application, then rotate the primary key in the Azure portal.

Azure 门户中的主密钥轮换 - 演示 NoSQL 数据库安全性

有关使用主密钥的代码示例Code sample to use a master key

以下代码示例演示如何使用 Cosmos DB 帐户终结点和主密钥来实例化 DocumentClient 并创建数据库。The following code sample illustrates how to use a Cosmos DB account endpoint and master key to instantiate a DocumentClient and create a database.

//Read the Azure Cosmos DB endpointUrl and authorization keys from config.
//These values are available from the Azure portal on the Azure Cosmos DB account blade under "Keys".
//Keep these values in a safe and secure location. Together they provide Administrative access to your Azure Cosmos DB account.

private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];

CosmosClient client = new CosmosClient(endpointUrl, authorizationKey);

资源令牌Resource tokens

资源令牌提供对数据库中应用程序资源的访问权限。Resource tokens provide access to the application resources within a database. 资源令牌:Resource tokens:

  • 提供对特定容器、分区键、文档、附件、存储过程、触发器和 UDF 的访问权限。Provide access to specific containers, partition keys, documents, attachments, stored procedures, triggers, and UDFs.
  • 用户授予对特定资源的权限时创建。Are created when a user is granted permissions to a specific resource.
  • 通过 POST、GET 或 PUT 调用操作权限资源时重新创建。Are recreated when a permission resource is acted upon on by POST, GET, or PUT call.
  • 使用专门针对用户、资源和权限构造的哈希资源令牌。Use a hash resource token specifically constructed for the user, resource, and permission.
  • 生存期受到可自定义的有效期的约束。Are time bound with a customizable validity period. 默认的有效期限为一小时。The default valid time span is one hour. 但是,可将令牌生存期显式指定为最长五个小时。Token lifetime, however, may be explicitly specified, up to a maximum of five hours.
  • 可以安全替代主密钥。Provide a safe alternative to giving out the master key.
  • 使客户端能够根据它们的权限读取、写入和删除 Cosmos DB 帐户中的资源。Enable clients to read, write, and delete resources in the Cosmos DB account according to the permissions they've been granted.

如果想要为不能通过主密钥得到信任的客户端提供对 Cosmos DB 帐户中资源的访问权限,可以使用资源令牌(通过创建 Cosmos DB 用户和权限来使用)。You can use a resource token (by creating Cosmos DB users and permissions) when you want to provide access to resources in your Cosmos DB account to a client that cannot be trusted with the master key.

Cosmos DB 资源令牌提供一种安全的替代方案,使客户端能够根据授予的权限读取、写入和删除 Cosmos DB 帐户中的资源,而无需主密钥或只读密钥。Cosmos DB resource tokens provide a safe alternative that enables clients to read, write, and delete resources in your Cosmos DB account according to the permissions you've granted, and without need for either a master or read only key.

以下是典型的设计模式,通过它可以请求、生成资源令牌并将其提供给客户端:Here is a typical design pattern whereby resource tokens may be requested, generated, and delivered to clients:

  1. 设置中间层服务,以用于移动应用程序共享用户照片。A mid-tier service is set up to serve a mobile application to share user photos.

  2. 中间层服务拥有 Cosmos DB 帐户的主密钥。The mid-tier service possesses the master key of the Cosmos DB account.

  3. 照片应用安装在最终用户移动设备上。The photo app is installed on end-user mobile devices.

  4. 登录时,照片应用使用中间层服务建立用户的标识。On login, the photo app establishes the identity of the user with the mid-tier service. 这种标识建立机制完全由应用程序决定。This mechanism of identity establishment is purely up to the application.

  5. 一旦建立标识,中间层服务就会基于标识请求权限。Once the identity is established, the mid-tier service requests permissions based on the identity.

  6. 中间层服务将资源令牌发送回手机应用。The mid-tier service sends a resource token back to the phone app.

  7. 手机应用可以继续使用该资源令牌以该资源令牌定义的权限按照该资源令牌允许的间隔直接访问 Cosmos DB 资源。The phone app can continue to use the resource token to directly access Cosmos DB resources with the permissions defined by the resource token and for the interval allowed by the resource token.

  8. 资源令牌到期后,后续请求收到 401 未经授权的异常。When the resource token expires, subsequent requests receive a 401 unauthorized exception. 此时,手机应用会重新建立标识,并请求新的资源令牌。At this point, the phone app re-establishes the identity and requests a new resource token.

    Azure Cosmos DB 资源令牌工作流

资源令牌的生成和管理由本机 Cosmos DB 客户端库处理;但是,如果使用 REST,必须构造请求/身份验证标头。Resource token generation and management is handled by the native Cosmos DB client libraries; however, if you use REST you must construct the request/authentication headers. 有关为 REST 创建身份验证标头的详细信息,请参阅 Cosmos DB 资源的访问控制或我们的 .NET SDKNode.js SDK 的源代码。For more information on creating authentication headers for REST, see Access Control on Cosmos DB Resources or the source code for our .NET SDK or Node.js SDK.

有关用于生成或代理资源令牌的中间层服务的示例,请参阅 ResourceTokenBroker 应用For an example of a middle tier service used to generate or broker resource tokens, see the ResourceTokenBroker app.


Azure Cosmos DB 用户与 Cosmos 数据库相关联。Azure Cosmos DB users are associated with a Cosmos database. 每个数据库可以包含零个或更多 Cosmos DB 用户。Each database can contain zero or more Cosmos DB users. 以下代码示例展示了如何使用 Azure Cosmos DB .NET SDK v3 创建 Cosmos DB 用户。The following code sample shows how to create a Cosmos DB user using the Azure Cosmos DB .NET SDK v3.

//Create a user.
Database database = benchmark.client.GetDatabase("SalesDatabase");

User user = await database.CreateUserAsync("User 1");


每个 Cosmos DB 用户都有一个 ReadAsync() 方法,可以使用此方法检索与用户关联的权限的列表。Each Cosmos DB user has a ReadAsync() method that can be used to retrieve the list of permissions associated with the user.

权限资源与用户相关联,并在容器以及分区键级别进行分配。A permission resource is associated with a user and assigned at the container as well as partition key level. 每个用户可能包含零个或多个权限。Each user may contain zero or more permissions. 用户在尝试访问某个特定容器或访问特定分区键中的数据时需要一个安全令牌,权限资源提供对该安全令牌的访问权限。A permission resource provides access to a security token that the user needs when trying to access a specific container or data in a specific partition key. 权限资源提供两种可用的访问级别:There are two available access levels that may be provided by a permission resource:

  • 所有:用户对资源拥有完全权限。All: The user has full permission on the resource.
  • 读取:用户只能读取资源的内容,但无法对资源执行写入、更新或删除操作。Read: The user can only read the contents of the resource but cannot perform write, update, or delete operations on the resource.


为了运行存储过程,用户必须对将在其中运行存储过程的容器具有全部权限。In order to run stored procedures the user must have the All permission on the container in which the stored procedure will be run.

有关创建权限的代码示例Code sample to create permission

以下代码示例演示如何创建权限资源、读取权限资源的资源令牌以及将权限与上面创建的用户关联。The following code sample shows how to create a permission resource, read the resource token of the permission resource, and associate the permissions with the user created above.

// Create a permission on a container and specific partition key value
Container container = client.GetContainer("SalesDatabase", "OrdersContainer");
    new PermissionProperties(
        id: "permissionUser1Orders",
        permissionMode: PermissionMode.All,
        container: benchmark.container,
        resourcePartitionKey: new PartitionKey("012345")));

有关读取用户权限的代码示例Code sample to read permission for user

下面的代码片段展示了如何检索与上面创建的用户关联的权限,并代表用户实例化一个新的 CosmosClient,作用域为单个分区键。The following code snippet shows how to retrieve the permission associated with the user created above and instantiate a new CosmosClient on behalf of the user, scoped to a single partition key.

//Read a permission, create user client session.
PermissionProperties permissionProperties = await user.GetPermission("permissionUser1Orders")

CosmosClient client = new CosmosClient(accountEndpoint: "MyEndpoint", authKeyOrResourceToken: permissionProperties.Token);

添加用户和分配角色Add users and assign roles

若要将 Azure Cosmos DB 帐户读者访问权限添加到用户帐户,请让订阅所有者在 Azure 门户执行以下步骤。To add Azure Cosmos DB account reader access to your user account, have a subscription owner perform the following steps in the Azure portal.

  1. 打开 Azure 门户,并选择 Azure Cosmos DB 帐户。Open the Azure portal, and select your Azure Cosmos DB account.
  2. 单击“访问控制(IAM)” 选项卡,然后单击“+ 添加角色分配” 。Click the Access control (IAM) tab, and then click + Add role assignment.
  3. 在“添加角色分配” 窗格中的“角色” 框中,选择“Cosmos DB 帐户读者角色” 。In the Add role assignment pane, in the Role box, select Cosmos DB Account Reader Role.
  4. 在“分配其访问权限” 框中,选择“Azure AD 用户、组或应用程序” 。In the Assign access to box, select Azure AD user, group, or application.
  5. 在你想要授予访问权限的目录中选择用户、组或应用程序。Select the user, group, or application in your directory to which you wish to grant access. 可以通过显示名称、电子邮件地址或对象标识符搜索目录。You can search the directory by display name, email address, or object identifiers. 所选用户、组或应用程序会显示在所选成员列表中。The selected user, group, or application appears in the selected members list.
  6. 单击“保存” 。Click Save.

实体现在便可以读取 Azure Cosmos DB 资源。The entity can now read Azure Cosmos DB resources.

删除或导出用户数据Delete or export user data

用户可使用 Azure Cosmos DB 搜索、选择、修改和删除数据库或集合中的任何个人数据。Azure Cosmos DB enables you to search, select, modify and delete any personal data located in database or collections. Azure Cosmos DB 提供用于查找和删除个人数据的 API,但用户应负责使用该 API 并定义擦除个人数据必需的逻辑。Azure Cosmos DB provides APIs to find and delete personal data however, it's your responsibility to use the APIs and define logic required to erase the personal data. 每个多模型 API(SQL、MongoDB、Gremlin、Cassandra、表)都包含不同的语言 SDK,这些 SDK 提供了各种用于搜索和删除个人数据的方法。Each multi-model API (SQL, MongoDB, Gremlin, Cassandra, Table) provides different language SDKs that contain methods to search and delete personal data. 还可启用生存时间 (TTL)功能在指定时间段后自动删除数据,不会产生任何额外费用。You can also enable the time to live (TTL) feature to delete data automatically after a specified period, without incurring any additional cost.


如果有兴趣查看或删除个人数据,请参阅 GDPR 的 Azure 数据使用者请求一文。If you’re interested in viewing or deleting personal data, please see the Azure Data Subject Requests for the GDPR article. 如需关于 GDPR 的常规信息,请参阅服务信任门户的 GDPR 部分If you’re looking for general info about GDPR, see the GDPR section of the Service Trust portal.

后续步骤Next steps