From f098a92186ea0e1f1531953e7aca33ae9c1ffda7 Mon Sep 17 00:00:00 2001 From: Priyanka-Microsoft Date: Thu, 31 Jul 2025 18:02:11 +0530 Subject: [PATCH] Replace DefaultAzureCredential with ManagedIdentityCredential --- .../AppConfiguration/AppConfiguration.cs | 3 +- .../Helpers/AzureCredentialHelper.cs | 34 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 App/backend-api/Microsoft.GS.DPS.Host/Helpers/AzureCredentialHelper.cs diff --git a/App/backend-api/Microsoft.GS.DPS.Host/AppConfiguration/AppConfiguration.cs b/App/backend-api/Microsoft.GS.DPS.Host/AppConfiguration/AppConfiguration.cs index 5bd0dc92..15c03131 100644 --- a/App/backend-api/Microsoft.GS.DPS.Host/AppConfiguration/AppConfiguration.cs +++ b/App/backend-api/Microsoft.GS.DPS.Host/AppConfiguration/AppConfiguration.cs @@ -1,6 +1,7 @@ using Azure.Identity; using Microsoft.Extensions.Azure; using Microsoft.GS.DPSHost.AppConfiguration; +using Microsoft.GS.DPSHost.Helpers; namespace Microsoft.GS.DPSHost.AppConfiguration { @@ -16,7 +17,7 @@ public static void Config(IHostApplicationBuilder builder) //Read AppConfiguration with managed Identity builder.Configuration.AddAzureAppConfiguration(options => { - options.Connect(new Uri(builder.Configuration["ConnectionStrings:AppConfig"]), new DefaultAzureCredential()); + options.Connect(new Uri(builder.Configuration["ConnectionStrings:AppConfig"]), AzureCredentialHelper.GetAzureCredential()); }); //Read ServiceConfiguration diff --git a/App/backend-api/Microsoft.GS.DPS.Host/Helpers/AzureCredentialHelper.cs b/App/backend-api/Microsoft.GS.DPS.Host/Helpers/AzureCredentialHelper.cs new file mode 100644 index 00000000..49fc01f5 --- /dev/null +++ b/App/backend-api/Microsoft.GS.DPS.Host/Helpers/AzureCredentialHelper.cs @@ -0,0 +1,34 @@ +using System; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; + +namespace Microsoft.GS.DPSHost.Helpers +{ + /// + /// The Azure Credential Helper class + /// + public static class AzureCredentialHelper + { + /// + /// Get the Azure Credentials based on the environment type + /// + /// The client Id in case of User assigned Managed identity + /// The Credential Object + public static TokenCredential GetAzureCredential(string? clientId = null) + { + var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; + + if (string.Equals(env, "Development", StringComparison.OrdinalIgnoreCase)) + { + return new DefaultAzureCredential(); // CodeQL [SM05139] Okay use of DefaultAzureCredential as it is only used in development + } + else + { + return clientId != null + ? new ManagedIdentityCredential(clientId) + : new ManagedIdentityCredential(); + } + } + } +} \ No newline at end of file