Skip to content

Instantly share code, notes, and snippets.

@beachside-project
Created June 28, 2021 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beachside-project/f0ab86e91304a7ad9b04649d3169afea to your computer and use it in GitHub Desktop.
Save beachside-project/f0ab86e91304a7ad9b04649d3169afea to your computer and use it in GitHub Desktop.
Cosmos DB RBAC sample
// NuGet: Azure.Identity (v1.4.0) と Microsoft.Azure.Cosmos (v3.20.0) を利用
using Azure.Identity;
using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;
namespace ConsoleApp
{
public class RbacForDataOperations
{
private readonly CosmosClient _cosmosClient;
// なんとなく Cosmos DB の endpoint をここで受け取ってます
public RbacForDataOperations(string endpoint)
{
var cosmosClientOptions = new CosmosClientOptions
{
SerializerOptions = new CosmosSerializationOptions
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
}
};
// NuGet: Azure.Identity が必要
// 2021年5月時点だとVSで複数アカウント持ってると認証できたりエラーになったりで非常にうざいので、PowerShell の認証を使う
var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
{
ExcludeVisualStudioCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeAzureCliCredential = true
});
// NuGet: Microsoft.Azure.Cosmos が必要
_cosmosClient = new CosmosClient(endpoint, credential, cosmosClientOptions);
}
public async Task RunAsync()
{
var managementContainer = _cosmosClient.GetContainer("ToDoList", "Management");
// 適当なデータを取ってくる(データが既に入ってる前提)
Item managementResult = await managementContainer.ReadItemAsync<Item>("1", new PartitionKey("A"));
Console.WriteLine($"Management: {managementResult.Id}:{managementResult.Title}");
var itemsContainer = _cosmosClient.GetContainer("ToDoList", "Items");
Item itemResult = await itemsContainer.ReadItemAsync<Item>("1", new PartitionKey("A"));
Console.WriteLine($"Items: {itemResult.Id}:{itemResult.Title}");
}
public class Item
{
public string Id { get; set; }
public string Title { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment