Skip to content

Commit 834ee3a

Browse files
authored
Merge pull request #101927 from markjbrown/users-perms-v3
Users perms v3
2 parents fe7eedd + 5929a31 commit 834ee3a

File tree

1 file changed

+46
-71
lines changed

1 file changed

+46
-71
lines changed
Lines changed: 46 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
---
22
title: Learn how to secure access to data in Azure Cosmos DB
33
description: Learn about access control concepts in Azure Cosmos DB, including master keys, read-only keys, users, and permissions.
4-
author: markjbrown
5-
ms.author: mjbrown
4+
author: thomasweiss
5+
ms.author: thweiss
66
ms.service: cosmos-db
77
ms.topic: conceptual
8-
ms.date: 05/21/2019
8+
ms.date: 01/21/2020
99

1010
---
1111
# Secure access to data in Azure Cosmos DB
@@ -21,15 +21,16 @@ Azure Cosmos DB uses two types of keys to authenticate users and provide access
2121

2222
<a id="master-keys"></a>
2323

24-
## Master keys
24+
## Master keys
25+
26+
Master keys provide access to all the administrative resources for the database account. Master keys:
2527

26-
Master keys provide access to all the administrative resources for the database account. Master keys:
2728
- Provide access to accounts, databases, users, and permissions.
2829
- Cannot be used to provide granular access to containers and documents.
2930
- Are created during the creation of an account.
3031
- Can be regenerated at any time.
3132

32-
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.
33+
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.
3334

3435
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.
3536

@@ -43,37 +44,29 @@ The process of rotating your master key is simple. Navigate to the Azure portal
4344

4445
### Code sample to use a master key
4546

46-
The following code sample illustrates how to use a Cosmos DB account endpoint and master key to instantiate a DocumentClient and create a database.
47+
The following code sample illustrates how to use a Cosmos DB account endpoint and master key to instantiate a DocumentClient and create a database.
4748

4849
```csharp
4950
//Read the Azure Cosmos DB endpointUrl and authorization keys from config.
5051
//These values are available from the Azure portal on the Azure Cosmos DB account blade under "Keys".
51-
//NB > Keep these values in a safe and secure location. Together they provide Administrative access to your DocDB account.
52+
//Keep these values in a safe and secure location. Together they provide Administrative access to your Azure Cosmos DB account.
5253
5354
private static readonly string endpointUrl = ConfigurationManager.AppSettings["EndPointUrl"];
5455
private static readonly string authorizationKey = ConfigurationManager.AppSettings["AuthorizationKey"];
5556

56-
client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
57-
58-
// Create Database
59-
Database database = await client.CreateDatabaseAsync(
60-
new Database
61-
{
62-
Id = databaseName
63-
});
57+
CosmosClient client = new CosmosClient(endpointUrl, authorizationKey);
6458
```
6559

66-
<a id="resource-tokens"></a>
67-
68-
## Resource tokens
60+
## Resource tokens <a id="resource-tokens"></a>
6961

7062
Resource tokens provide access to the application resources within a database. Resource tokens:
63+
7164
- Provide access to specific containers, partition keys, documents, attachments, stored procedures, triggers, and UDFs.
7265
- Are created when a [user](#users) is granted [permissions](#permissions) to a specific resource.
7366
- Are recreated when a permission resource is acted upon on by POST, GET, or PUT call.
7467
- Use a hash resource token specifically constructed for the user, resource, and permission.
75-
- Are time bound with a customizable validity period. The default valid timespan is one hour. Token lifetime, however, may be explicitly specified, up to a maximum of five hours.
76-
- Provide a safe alternative to giving out the master key.
68+
- 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.
69+
- Provide a safe alternative to giving out the master key.
7770
- Enable clients to read, write, and delete resources in the Cosmos DB account according to the permissions they've been granted.
7871

7972
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.
@@ -82,90 +75,69 @@ Cosmos DB resource tokens provide a safe alternative that enables clients to rea
8275

8376
Here is a typical design pattern whereby resource tokens may be requested, generated, and delivered to clients:
8477

85-
1. A mid-tier service is set up to serve a mobile application to share user photos.
78+
1. A mid-tier service is set up to serve a mobile application to share user photos.
8679
2. The mid-tier service possesses the master key of the Cosmos DB account.
87-
3. The photo app is installed on end-user mobile devices.
80+
3. The photo app is installed on end-user mobile devices.
8881
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.
8982
5. Once the identity is established, the mid-tier service requests permissions based on the identity.
9083
6. The mid-tier service sends a resource token back to the phone app.
91-
7. 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.
84+
7. 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.
9285
8. 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.
9386

9487
![Azure Cosmos DB resource tokens workflow](./media/secure-access-to-data/resourcekeyworkflow.png)
9588

96-
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. For more information on creating authentication headers for REST, see [Access Control on Cosmos DB Resources](https://docs.microsoft.com/rest/api/cosmos-db/access-control-on-cosmosdb-resources) or the [source code for our SDKs](https://github.com/Azure/azure-documentdb-node/blob/master/source/lib/auth.js).
89+
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. For more information on creating authentication headers for REST, see [Access Control on Cosmos DB Resources](https://docs.microsoft.com/rest/api/cosmos-db/access-control-on-cosmosdb-resources) or the source code for our [.NET SDK](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos/src/AuthorizationHelper.cs) or [Node.js SDK](https://github.com/Azure/azure-cosmos-js/blob/master/src/auth.ts).
9790

9891
For an example of a middle tier service used to generate or broker resource tokens, see the [ResourceTokenBroker app](https://github.com/Azure/azure-documentdb-dotnet/tree/master/samples/xamarin/UserItems/ResourceTokenBroker/ResourceTokenBroker/Controllers).
9992

100-
<a id="users"></a>
93+
## Users<a id="users"></a>
10194

102-
## Users
103-
Cosmos DB users are associated with a Cosmos database. Each database can contain zero or more Cosmos DB users. The following code sample shows how to create a Cosmos DB user resource.
95+
Azure Cosmos DB users are associated with a Cosmos database. Each database can contain zero or more Cosmos DB users. The following code sample shows how to create a Cosmos DB user using the [Azure Cosmos DB .NET SDK v3](https://github.com/Azure/azure-cosmos-dotnet-v3/tree/master/Microsoft.Azure.Cosmos.Samples/Usage/UserManagement).
10496

10597
```csharp
10698
//Create a user.
107-
User docUser = new User
108-
{
109-
Id = "mobileuser"
110-
};
99+
Database database = benchmark.client.GetDatabase("SalesDatabase");
111100

112-
docUser = await client.CreateUserAsync(UriFactory.CreateDatabaseUri("db"), docUser);
101+
User user = await database.CreateUserAsync("User 1");
113102
```
114103

115104
> [!NOTE]
116-
> Each Cosmos DB user has a PermissionsLink property that can be used to retrieve the list of [permissions](#permissions) associated with the user.
117-
>
118-
>
105+
> Each Cosmos DB user has a ReadAsync() method that can be used to retrieve the list of [permissions](#permissions) associated with the user.
119106
120-
<a id="permissions"></a>
107+
## Permissions<a id="permissions"></a>
121108

122-
## Permissions
123-
A Cosmos DB permission resource is associated with a Cosmos DB user. Each user may contain zero or more Cosmos DB permissions. A permission resource provides access to a security token that the user needs when trying to access a specific application resource.
124-
There are two available access levels that may be provided by a permission resource:
109+
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:
125110

126-
* All: The user has full permission on the resource.
127-
* Read: The user can only read the contents of the resource but cannot perform write, update, or delete operations on the resource.
111+
- All: The user has full permission on the resource.
112+
- Read: The user can only read the contents of the resource but cannot perform write, update, or delete operations on the resource.
128113

129114
> [!NOTE]
130-
> In order to run Cosmos DB stored procedures the user must have the All permission on the container in which the stored procedure will be run.
131-
>
132-
>
115+
> In order to run stored procedures the user must have the All permission on the container in which the stored procedure will be run.
133116
134117
### Code sample to create permission
135118

136119
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](#users) created above.
137120

138121
```csharp
139-
// Create a permission.
140-
Permission docPermission = new Permission
141-
{
142-
PermissionMode = PermissionMode.Read,
143-
ResourceLink = UriFactory.CreateDocumentCollectionUri("db", "collection"),
144-
Id = "readperm"
145-
};
146-
147-
docPermission = await client.CreatePermissionAsync(UriFactory.CreateUserUri("db", "user"), docPermission);
148-
Console.WriteLine(docPermission.Id + " has token of: " + docPermission.Token);
122+
// Create a permission on a container and specific partition key value
123+
Container container = client.GetContainer("SalesDatabase", "OrdersContainer");
124+
user.CreatePermissionAsync(
125+
new PermissionProperties(
126+
id: "permissionUser1Orders",
127+
permissionMode: PermissionMode.All,
128+
container: benchmark.container,
129+
resourcePartitionKey: new PartitionKey("012345")));
149130
```
150131

151-
If you have specified a partition key for your collection, then the permission for collection, document, and attachment resources must also include the ResourcePartitionKey in addition to the ResourceLink.
132+
### Code sample to read permission for user
152133

153-
### Code sample to read permissions for user
154-
155-
To easily obtain all permission resources associated with a particular user, Cosmos DB makes available a permission feed for each user object. The following code snippet shows how to retrieve the permission associated with the user created above, construct a permission list, and instantiate a new DocumentClient on behalf of the user.
134+
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.
156135

157136
```csharp
158-
//Read a permission feed.
159-
FeedResponse<Permission> permFeed = await client.ReadPermissionFeedAsync(
160-
UriFactory.CreateUserUri("db", "myUser"));
161-
List<Permission> permList = new List<Permission>();
162-
163-
foreach (Permission perm in permFeed)
164-
{
165-
permList.Add(perm);
166-
}
137+
//Read a permission, create user client session.
138+
PermissionProperties permissionProperties = await user.GetPermission("permissionUser1Orders")
167139

168-
DocumentClient userClient = new DocumentClient(new Uri(endpointUrl), permList);
140+
CosmosClient client = new CosmosClient(accountEndpoint: "MyEndpoint", authKeyOrResourceToken: permissionProperties.Token);
169141
```
170142

171143
## Add users and assign roles
@@ -183,11 +155,14 @@ To add Azure Cosmos DB account reader access to your user account, have a subscr
183155
The entity can now read Azure Cosmos DB resources.
184156

185157
## Delete or export user data
158+
186159
Azure Cosmos DB enables you to search, select, modify and delete any personal data located in database or collections. 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.
187160
Each multi-model API (SQL, MongoDB, Gremlin, Cassandra, Table) provides different language SDKs that contain methods to search and delete personal data. You can also enable the [time to live (TTL)](time-to-live.md) feature to delete data automatically after a specified period, without incurring any additional cost.
188161

189162
[!INCLUDE [GDPR-related guidance](../../includes/gdpr-dsr-and-stp-note.md)]
190163

191164
## Next steps
192-
* To learn more about Cosmos database security, see [Cosmos DB: Database security](database-security.md).
193-
* To learn how to construct Azure Cosmos DB authorization tokens, see [Access Control on Azure Cosmos DB Resources](https://docs.microsoft.com/rest/api/cosmos-db/access-control-on-cosmosdb-resources).
165+
166+
- To learn more about Cosmos database security, see [Cosmos DB Database security](database-security.md).
167+
- To learn how to construct Azure Cosmos DB authorization tokens, see [Access Control on Azure Cosmos DB Resources](https://docs.microsoft.com/rest/api/cosmos-db/access-control-on-cosmosdb-resources).
168+
- User management samples with users and permissions, [.NET SDK v3 user management samples](https://github.com/Azure/azure-cosmos-dotnet-v3/blob/master/Microsoft.Azure.Cosmos.Samples/Usage/UserManagement/UserManagementProgram.cs)

0 commit comments

Comments
 (0)