-
Notifications
You must be signed in to change notification settings - Fork 210
Closed
Labels
Description
Topic: Supporting Chained Certificates from Azure Key Vault
When retrieving a certificate from Azure Key Vault using the built in endpoint
https://docs.microsoft.com/en-us/rest/api/keyvault/getcertificate/getcertificate
Which would look something like the following
For a specific version:
https://myvault.vault.azure.net/secrets/selfSignedCert01/f60f2a4f8ae442cfb41ca2090bd4b769
For the latest version:
```https://myvault.vault.azure.net/secrets/selfSignedCert01``
The response is a base64 encoded PFX file.
To be able to load it properly into the library I suggest using the following snippet
import base64
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import PrivateFormat
from cryptography.hazmat.primitives.serialization import NoEncryption
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
import msal
config = {
"authority": "https://login.microsoftonline.com/Enter_the_Tenant_Name_Here",
"client_id": "your_client_id",
"scope": ["https://graph.microsoft.com/.default"],
"thumbprint": "790E... The thumbprint generated by AAD when you upload your public cert",
"private_key_file": "filename.pem",
"endpoint": "https://graph.microsoft.com/v1.0/users"
}
credential = DefaultAzureCredential()
client = SecretClient(vault_url=KVUri, credential=credential)
retrieved_secret = client.get_secret(secretName)
# unbase 64 and parse as a pkcs12 file
# returns a list of certificates in private key of leaf (0 index) to root public (-1 index) order
private_key = pkcs12.load_key_and_certificates(base64.b64decode(retrieved_secret.value), password=None, backend=default_backend())[0].private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption())
# get public cert of leaf and generate thumbprint
thumbprint = pkcs12.load_key_and_certificates(base64.b64decode(retrieved_secret.value), password=None, backend=default_backend())[1].fingerprint(hashes.SHA1()).hex()
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential={"thumbprint": thumbprint, "private_key": private_key}
)rayluo