C# .NET Framework 4.7.2 in VS 2019 - keep out my clientID and client secret / gitignore / Key Vault

1k views Asked by At

I am a new to #C, therefore excuse my question, which will be probably very easy to you. I am trying to get my clientID, clientSecret and tenantID out of the main source control, but I am not sure at all how to do that. I have seen some methods for .NET Core with Connected Services in Visual Studio, but this is not really available for .NET Framework 4.7.2. I am not confident in setting the config file neither. I have created a resource group on Azure Portal, but I am not sure how to get this key vault working.

The code below represents a working code acquiring a token, the issue I have is to hide those hardcoded strings.

Many thanks for your answer

        private static string GetToken()
        {

            string clientID = "xxxad43f-c825-491f-9130-8cc4da1d1111";
            string clientSecret = "dRbIT5Wn4@u=55L@fLnYRNuDYrFD@111";
            string tenantID = "4ae48b41-0137-4599-8661-fc641fe77111";
            var app = ConfidentialClientApplicationBuilder
                .Create(clientID)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token"))
                .Build();

            var ApiID = "api://dddd-api";
            var scopes = new[] { ApiID + "/.default" };

            var result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;

            if (result == null)
                throw new Exception("Could not acquire token");

            return result.AccessToken;
        }
1

There are 1 answers

0
Tom Yao On

You can set the value as environment variables and use Environment.GetEnvironmentVariable("<variable name>") to get them.

string clientID = Environment.GetEnvironmentVariable("AZURE_CLIENT_ID");
string clientSecret = Environment.GetEnvironmentVariable("AZURE_CLIENT_SECRET");
string tenantID = Environment.GetEnvironmentVariable("AZURE_TENANT_ID");