using Azure.Core; using Azure.Identity; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Authentication.Oidc; var client = new MongoClient(GetMongoClientSettings()); var database = client.GetDatabase("<...>"); var collection = database.GetCollection("<...>"); while (true) { try { var objectId = new ObjectId("5efa062d17c8a20001733d7e"); var filter = Builders.Filter.Eq("_id", objectId); var document = await collection.Find(filter).FirstOrDefaultAsync(); Console.WriteLine($"*****************\n{DateTime.UtcNow}\n*****************\n"); await Task.Delay(1000); } catch (Exception e) { Console.WriteLine(e); } } static MongoClientSettings GetMongoClientSettings() { MongoClientSettings mongoClientSettings = MongoClientSettings.FromConnectionString("mongodb+srv://<...>.azure.mongodb.net/admin?authSource=$external&authMechanism=MONGODB-OIDC"); mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new OidcCallback("<...>")); mongoClientSettings.MaxConnectionLifeTime = TimeSpan.FromSeconds(5); return mongoClientSettings; } class OidcCallback(string oidcApplicationId) : IOidcCallback { public OidcAccessToken GetOidcAccessToken(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = new DefaultAzureCredential().GetToken(new TokenRequestContext([oidcApplicationId]), cancellationToken); return new(token.Token, expiresIn: null); } public async Task GetOidcAccessTokenAsync(OidcCallbackParameters parameters, CancellationToken cancellationToken) { AccessToken token = await new DefaultAzureCredential().GetTokenAsync(new TokenRequestContext([oidcApplicationId]), cancellationToken); return new(token.Token, expiresIn: TimeSpan.FromSeconds(5)); } }