Skip to content

Instantly share code, notes, and snippets.

@seesharprun
Last active April 25, 2025 03:59
Show Gist options
  • Save seesharprun/43c0b23563ff0180933cf5aaa094bad1 to your computer and use it in GitHub Desktop.
Save seesharprun/43c0b23563ff0180933cf5aaa094bad1 to your computer and use it in GitHub Desktop.
C# console how-to guide for Entra auth in Azure Cosmos DB for MongoDB vCore
using Azure.Core;
using MongoDB.Driver.Authentication.Oidc;
internal sealed class AzureIdentityTokenHandler(
TokenCredential credential,
string tenantId,
string[] scopes
) : IOidcCallback
{
public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken)
{
AccessToken token = credential.GetToken(
new TokenRequestContext(scopes, tenantId: tenantId),
cancellationToken
);
return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
}
public async Task<OidcAccessToken> GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken)
{
AccessToken token = await credential.GetTokenAsync(
new TokenRequestContext(scopes, parentRequestId: null, tenantId: tenantId),
cancellationToken
);
return new OidcAccessToken(token.Token, token.ExpiresOn - DateTimeOffset.UtcNow);
}
}
internal sealed record Product(
string id,
string category,
string name,
int quantity,
decimal price,
bool clearance
);
using Azure.Identity;
using MongoDB.Driver;
DefaultAzureCredential credential = new();
string accountName = "<azure-cosmos-db-mongodb-vcore-account-name>";
MongoUrl url = MongoUrl.Create($"mongodb+srv://${accountName}.global.mongocluster.cosmos.azure.com'/");
MongoClientSettings settings = MongoClientSettings.FromUrl(url);
settings.UseTls = true;
settings.RetryWrites = false;
settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(2);
string tenantId = "<microsoft-entra-tenant-id>";
string[] scopes = ["https://ossrdbms-aad.database.windows.net/.default"];
AzureIdentityTokenHandler tokenHandler = new(credential, tenantId, scopes);
settings.Credential = MongoCredential.CreateOidcCredential(tokenHandler);
settings.Freeze();
MongoClient client = new(settings);
string databaseName = "<database-name>";
IMongoDatabase database = client.GetDatabase(databaseName);
string collectionName = "<collection-name>";
IMongoCollection<Product> collection = database.GetCollection<Product>(collectionName);
{
Product product = new(
id: "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
category: "gear-surf-surfboards",
name: "Yamba Surfboard",
quantity: 12,
price: 850.00m,
clearance: false
);
await collection.ReplaceOneAsync(
doc => doc.id == product.id,
product,
new ReplaceOptions { IsUpsert = true }
);
}
{
List<Product> products = await collection.Find(
doc => doc.category == "gear-surf-surfboards"
).ToListAsync();
foreach (Product product in products)
{
Console.WriteLine(product);
}
}
{
await collection.DeleteOneAsync(
doc => doc.id == "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb"
);
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.13.2" />
<PackageReference Include="MongoDB.Driver" Version="3.3.0" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment