Use certificate in Azure Key Vault to sign IdentityServer4 - azure

I've uploaded a pfx certificate as a secret to my Azure Portal and I now want to use this to sign the credentials in IdentityServer4.
I've got reference to the vault in the startup of the api using:
builder.AddAzureKeyVault(
$"https://{config["Vault"]}.vault.azure.net/",
config["ClientId"],
config["ClientSecret"]);
But not too sure how to get the certificate out to pass to:
services.AddIdentityServer()
.AddSigningCredential(...)
Is it possibly to be able to reference the certificate directly from the key vault, or do I need to deploy the cert to the web app the api is running on?
Thanks

You are already building the IConfiguration object, so you can reference the pfx key just like you would reference any other object from the configuration.
If the key is in the keyvault you can reference it something like:
// Name of your pfx in the keyvault.
var key = _configuration["pfx"];
var pfxBytes = Convert.FromBase64String(key);
// Create the certificate.
var cert = new X509Certificate2(pfxBytes);
services.AddIdentityServer()
.AddSigningCredential(cert);
I would recommend using the keyvault for this but you could decide to upload the pfx to the certificate store of the web app. You can do this in Azure by going to your web app -> SSL Certificates -> Upload certificate and enter the password. Go to the Application Settings and add the app setting WEBSITE_LOAD_CERTIFICATES : <thumbprint>. The last thing you would do is retrieve the certificate from the store and add it again like AddSigningCredential(cert);.

Related

Azure App Service Fails to Find Newly Created Certificate

I have an Azure app service I did not create but now maintain. The app service finds a certificate in a Key Vault by thumbprint and in turn uses that to get a token for doing some SQL work via nightly jobs.
It appears the certificate was set to auto renew after 80% of its valid date (12 months). The day the cert renewed my nightly jobs started to fail. I'm reasonably certain the new certificate is at the root of the problem.
As best I can tell it designed to work like this:
Job fires via Azure Logic App
annomyous POST to a reports processing API (end result should be .PDF report creation for email atachment)
API has Appsetting.json that contains the current certificates thumbprint
Thumbprint is used in the line of code below to find the certificate in the cert store
Cert is used to aquire access token and perform work
When I install both the old certificate and the new certificate on my local machine and run the entire process it works find with the old certificate and fails on this line with the new auto-generated certificate. It also fails with any new certificates I try to make in Azure and export from Azure and import to my dev machine. I've double/triple checked the appsettings to make sure the Thumbprint in question is correct and updated.
var signingCert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(x => x.Thumbprint == _appSettings.AzureAD.CertificateThumbprint);
When this was configured a year ago the process was to go into App Service, TLS/SSL setting blade, select Private Key Certificates (.pfx) and finally + Import Key Vault Certificate.
From there you selected the Key Vault and Certificate, then changed the Appsettings.Json to have the new Thumbprint.
Why will it work with the old (soon to expire) certificate and corresponding Thumbprint entry into appsettings but fails to work with any newly created certificates and corresponding correct Thumbprint entry?
I've looked at the Configuration for the App Service in question and it has the following setting when I understand is supposed to let the app service see all certificates registered to it, right?
WEBSITE_LOAD_CERTIFICATES = *
EDIT:
After some more testing I find that any cert I export form Azure and import on my computer will successfully iterate the cert store and find any Certificate I provide a valid Thumbprint. What it won't do is use that cert to obtain a access token. The complete code is below.
The certificate that is due to expire soon will get a proper access token and run the rest of the process by getting the proper data from the DB.
The exception I get with all the other certificates suggest something about base64 encoding but I can't quite figure that out. Any ideas?
Exception for all but the original certificate:
Client assertion contains an invalid signature
Successful Access token with this code only with original certificate:
private async Task<string> GetDatabaseTokenFromCert()
{
X509Certificate2 cert;
var store = new X509Store(StoreLocation.CurrentUser);
var authContext = new AuthenticationContext(_appSettings.AzureAD.AADInstance + _appSettings.AzureAD.TenantId);
try
{
store.Open(OpenFlags.ReadOnly);
var signingCert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(x => x.Thumbprint == _appSettings.AzureAD.CertificateThumbprint);
if (signingCert == null)
{
throw new FileNotFoundException("Cannot locate certificate for DB access!", _appSettings.AzureAD.CertificateThumbprint);
}
cert = signingCert;
}
finally
{
store.Close();
}
var certCred = new ClientAssertionCertificate(_appSettings.AzureAD.ClientId, cert);
var result = await Retry(() => authContext.AcquireTokenAsync(_appSettings.SqlConfig.ResourceId, certCred));
return result?.AccessToken;
}
Turns out you need to also add the new certificate to the app registration. As a .cer file without the private key, obviously.
So if you get the error message:
AADSTS700027: Client assertion contains an invalid signature. [Reason - The key was not found., Thumbprint of key used by client: 'YourNewCert'
Go to Key Vault, export new cert as .cer file and import it into the App Service that is trying to obtain the Access token from AcquireTokenAsync
In my case the order of operation is:
Logic app fires off anonymous call as a POST to web API
Web API uses Thumbprint of Cert in question via appsetting.json
Finds cert with thumbprint that is in App Registration of the web API
AcquireTokenAsync takes Azure info and Cert and returns Access Token
This will work or fail on this line of original post
var result = await Retry(() => authContext.AcquireTokenAsync(_appSettings.SqlConfig.ResourceId, certCred));

How can i renew a Host Key in Azure function App without losing the link to the Key Vault?

I have a Function App Hosted in Azure. I access the functions via a Key in the Host Keys that i created , MyKey. This is linked to a secret in the KeyVault via the following format :
#Microsoft.KeyVault(SecretUri=secret_uri_with_version)
Now if the Key inside the function App is renewed, I lose the edited value as above and it is replaced with a random key value .
How can i make it so that if someone renews the key in the function app then the link to the Key Vault is not lost ?

Read secret stored in Key Vault from an App Service running a container

I've created an App Service that is running a container running Identity Server. This container needs a certificate that I'm loading from Key Vault. To get the content of the certificate what I've done is:
Upload the certificate into Key Vault
Access the content accessing the secret endpoint of the Key Vault (https://mykeyvault.vault.azure.net/secrets/IdentityCert)
In my first attempt, I was storing just the URI of the secret in the App Settings and try to get the value using the following code:
var azureServiceTokenProvider = new AzureServiceTokenProvider();
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var cert = keyVaultClient
.GetSecretAsync(
Env.GetString("CERTIFICATE_KEY_VAULT_KEY"))
.ConfigureAwait(false).GetAwaiter().GetResult();
identityServerBuilder.AddSigningCredential(new X509Certificate2(Convert.FromBase64String(cert.Value)));
This works if I deploy the code into a VM. But it doesn't if I deploy the code into an App Service running a container. So I decided to try another option which is to use the Key Vault reference thing. So, I've created a new App Settings like this:
CERTIFICATE_CONTENT = #Microsoft.KeyVault(SecretUri=https://mykeyvault.vault.azure.net/secrets/IdentityCert/5221036c6b734d5fa69cba29976a8592)
And then just use this value inside my code:
var certificateContent = Env.GetString("CERTIFICATE_CONTENT");
identityServerBuilder.AddSigningCredential(new X509Certificate2(Convert.FromBase64String(certificateContent)));
But this doesn't work either.
I've enabled the managed identity in the App Service and added it to the Access Policies in the Key Vault.
How can I get the value from Key Vault? Is there anything I'm missing?
So, the error was the way I was adding the new access policy. I was selecting the principal Id and the Authorized application. It turns out that I only need to select the principal, leaving the Authorized application as "None selected".

Upload cloud service certificate from keyvault

I have uploaded the SSl certificate to keyvault. Now I wanted to upload this certificate to my Cloud service
With this API I am able to access the Cert from keyvault
GET https://{vaultBaseUrl}/secrets/{secret-name}/{secret-version}?api-version={api-version}
But to upload certifcate, I need the password too.
"path": "subscriptions/%sub_Id%/resourceGroups/%rg_Name%/providers/Microsoft.ClassicCompute/domainNames/%cloudService_Name%/servicecertificates/SHA1-%THUMBPRINT%",
"body": {
"thumbprintAlgorithm": "SHA1",
"thumbprint": "%THUMBPRINT%",
"data": "%base64encodedcert%",
"certificateFormat": "pfx",
"password": "password" << this is in plain text I believe
}
How to get the password from keyvault or upload service certificate without password or with secret URI ?
When you need to pass a secure value (like a password) as a parameter during deployment, you can retrieve the value from an Azure Key Vault. You retrieve the value by referencing the key vault and secret in your parameter file. The value is never exposed because you only reference its key vault ID. You do not need to manually enter the value for the secret each time you deploy the resources.
For more details, refer to this documentation. Use Key Vault to pass secure parameter.
Also, check the Azure Key Vault REST API reference for examples.

Support for user certificate authentification in Azure AD

I'am searching for public/private key-based authentication for users with Azure-ActiveDirectory but can't find any hints in Azure AD Authentification Scenarios. Every user should bring his own key pair. Any suggestions how to achieve it?
Azure AD supports OAuth 2.0 to authorize the third-party apps and the OAuth 2.0 support to acquire the token using the app’s client credential.
There are two ways to acquire the token for the client credential flow.
First is that using the keys which generated by the Azure portal like figure below:
And here is a figure about token request using the key(client_secret):
Another way is using the cert. Technical speaking, the cert is a pair of public/private key. We will store the information of public key with the app. When we require to prove we are the owner of the third-party apps, we need to sign the message with the private key and Azure AD with verify the messages with public key.
To store the cert information with apps, we need to change the manifest of app. Here is the detail steps to use a self-signed certificate from here:
1.Generate a self-signed certificate:
makecert -r -pe -n "CN=MyCompanyName MyAppName Cert" -b 03/15/2015 -e 03/15/2017 -ss my -len 2048
2.Open the Certificates MMC snap-in and connect to your user account.
3.Find the new certificate in the Personal folder and export the public key to a base64-encoded file (for example, mycompanyname.cer). Your application will use this certificate to communicate with AAD, so make sure you retain access to the private key as well.
Note You can use Windows PowerShell to extract the thumbprint and base64-encoded public key. Other platforms provide similar tools to retrieve properties of certificates.
4.From the Windows PowerShell prompt, type and run the following:
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cer.Import("mycer.cer")
$bin = $cer.GetRawCertData()
$base64Value = [System.Convert]::ToBase64String($bin)
$bin = $cer.GetCertHash()
$base64Thumbprint = [System.Convert]::ToBase64String($bin)
$keyid = [System.Guid]::NewGuid().ToString()
5.Store the values for $base64Thumbprint, $base64Value and $keyid, to be used when you update your application manifest in the next set of steps.
Using the values extracted from the certificate and the generated key ID, you must now update your application manifest in Azure AD.
6.In the Azure Management Portal, select your application and choose Configure in the top menu.
7.In the command bar, click Manage manifest and select Download Manifest.
8.Open the downloaded manifest for editing and replace the empty KeyCredentials property with the following JSON:
"keyCredentials": [
{
"customKeyIdentifier": "$base64Thumbprint_from_above",
"keyId": "$keyid_from_above",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": "$base64Value_from_above"
}
],
9.Save your changes and upload the updated manifest by clicking Manage manifest in the command bar, selectingUpload manifest, browsing to your updated manifest file, and then selecting it.
And below is the figure about token request using the cert:
In the article above, it generate the client_assertion from scratch. We can also use the ADAL library to help us and authenticate for a daemon apps:
string authority = $"https://login.microsoftonline.com/{tenant}";
var thumbprint="";
X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates;
X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, thumbprint, false);
X509Certificate2 cert = fcollection[0];
var certCred = new ClientAssertionCertificate(clientId, cert);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(resource, certCred);
}
catch (Exception ex)
{
}
return result.AccessToken;
And if you want to use the cert to authorize for the OAuth2.0 code grant flow, you also can refer the code sample here.
If you're looking for a programmatic method to authenticate users (not apps) in Azure AD using certificates, this is not currently possible.
It is possible to do certificate-based authentication in AD FS (e.g.), and it is possible to federate authentication for users from Azure AD to AD FS. However, this requires the overhead of Windows Server AD, Azure AD Connect and AD FS, and I don't think the federated authentication can be achieved in a programmatic way (i.e. without prompting the user to choose a certificate).

Resources