diff --git a/ServerlessLibraryAPI/CosmosLibraryStore.cs b/ServerlessLibraryAPI/CosmosLibraryStore.cs index aaf7a61..7740fa9 100644 --- a/ServerlessLibraryAPI/CosmosLibraryStore.cs +++ b/ServerlessLibraryAPI/CosmosLibraryStore.cs @@ -1,8 +1,9 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; using Microsoft.Azure.Cosmos; -using Microsoft.Azure.Cosmos.Fluent; using ServerlessLibrary.Models; namespace ServerlessLibrary @@ -28,7 +29,7 @@ async public Task> GetAllItems() return libraryItems.ToList(); } } - + /// /// Cosmos db APIs /// @@ -98,10 +99,37 @@ public static void Initialize() { if (container == null) { - CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder( - ServerlessLibrarySettings.CosmosEndpoint, - ServerlessLibrarySettings.CosmosAuthkey); - CosmosClient client = cosmosClientBuilder.Build(); + CosmosClient client; + + // Use DefaultAzureCredential as the default authentication method (recommended for Azure workloads) + if (!string.IsNullOrEmpty(ServerlessLibrarySettings.CosmosEndpoint)) + { + try + { + // Create DefaultAzureCredential with basic options compatible with .NET Core 2.1 + TokenCredential credential = new DefaultAzureCredential(); + client = new CosmosClient(ServerlessLibrarySettings.CosmosEndpoint, credential); + } + catch + { + // Fallback to connection string authentication if DefaultAzureCredential fails + if (!string.IsNullOrEmpty(ServerlessLibrarySettings.CosmosAuthkey)) + { + client = new CosmosClient( + ServerlessLibrarySettings.CosmosEndpoint, + ServerlessLibrarySettings.CosmosAuthkey); + } + else + { + throw new System.InvalidOperationException( + "Unable to authenticate with Cosmos DB. Ensure either managed identity is configured or CosmosAuthkey is provided."); + } + } + } + else + { + throw new System.InvalidOperationException("CosmosEndpoint must be configured."); + } DatabaseResponse databaseResponse = client.CreateDatabaseIfNotExistsAsync(DatabaseId).Result; Database database = databaseResponse; diff --git a/ServerlessLibraryAPI/ServerlessLibraryAPI.csproj b/ServerlessLibraryAPI/ServerlessLibraryAPI.csproj index 40b76bf..36903ac 100644 --- a/ServerlessLibraryAPI/ServerlessLibraryAPI.csproj +++ b/ServerlessLibraryAPI/ServerlessLibraryAPI.csproj @@ -11,16 +11,20 @@ /subscriptions/7c1b7bab-00b2-4cb7-924e-205c4f411810/resourcegroups/Default-ApplicationInsights-EastUS/providers/microsoft.insights/components/ServerlessLibrary 235c2497-239d-47f0-8ea7-af2dd2416d95 ServerlessLibrary + true + false + - + + - +