I am currently using a client secret with an Azure app registration to access an Azure Media service from an App Service. I want to replace the client secret with a certificate as the certificate will last longer. I have successfully generated a certificate and uploaded it to the app registration.
Using the client secret seems straight forward. I create environment variables (in the app service configuration or local.settings.json) for the app registration client ID, app registration client secret and tenant ID and then use the following code:
private async Task<ServiceClientCredentials> GetCredentialsAsync(string aadClientId, string aadSecret, string aadTenantId)
{
ClientCredential clientCredential = new ClientCredential(aadClientId, aadSecret);
return await ApplicationTokenProvider.LoginSilentAsync(aadTenantId, clientCredential,
ActiveDirectoryServiceSettings.Azure);
}
How do I change this code to use the certificate?
CodePudding user response:
I tried to reproduce the same in my environment and got the results like below:
I created an Azure AD Application and uploaded a certificate:
To generate the access token using certificate, you can declare the below parameters in your app.settings
file:
"AzureAd": {
"Scope":"https://graph.microsoft/.default",
"Instance":"https://login.microsoftonline.com/",
"Domain":"XXX.onmicrosoft.com",
"TenantId":"YourTenantID",
"ClientId":"ClientID",
"ClientCertificates": [
{
"SourceType":"KeyVault",
"KeyVaultUrl":"https://xxx.vault.azure.net",
"KeyVaultCertificateName":"certName"
}
]
},
You can refer this blog by damienbod to know how generate the access token in detail.
I tried to generate the access token in Postman by using parameters like below:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:clientId
client_assertion_type:urn:ietf:params:oauth:client-assertion-type:jwt-bearer
scope:https://graph.microsoft.com/.default
grant_type:client_credentials
client_assertion:client_assertion
References:
Azure AD OAuth client credential flow with certificate by Nicola Delfino
App that calls MSGraph with a certificate by christosmatskas