Anyway, when we want to access Azure KeyVault secret, we have to grant access policy. And we can grant access policy for Azure AD applications, specific User/Group, and ManagedIdentity instance generally.
When we want to use DefauleAzureCredential
, we have the option to set client id/client secret/tenant id
for an Azure AD app, since you don't have the client secret, maybe this is not available for you. Then we can also use user credential, I think it's good for us to use this when we test the code in local machine, only we need to do is adding access policy for a user
, then sign in Visual Studio with that user
, then we can simply get authorized to access the vault secret by code below:
public async Task<string> IndexAsync()
{
const string secretName = "clientsecret";
var kvUri = "https://keyvaultname.vault.azure.net/";
var a = new DefaultAzureCredential();
var client = new SecretClient(new Uri(kvUri), a);
var secret = await client.GetSecretAsync(secretName);
string secretVaule = secret.Value.Value;
return secretVaule ;
}

We can also use ManagedIdentity, but this requires the app to be host in Azure. Just following this official document. It also contains a sample inside the document.
builder.Configuration.AddAzureKeyVault(
new Uri("https://vaultName.vault.azure.net/"),
new DefaultAzureCredential(
new DefaultAzureCredentialOptions { ManagedIdentityClientId = "userManagedIdentityClientId" }//required when using user ManagedIdentity
));