Search code examples
c#azure-functionsazure-api-managementazure-management-api

Using C# to bind a new certificate for Custom Domains from Azure Api Management Service


I have tried to get the APIM Client and I figured it out that with apiManagement.Service.HostnameConfigurations I can get some information about what is it inside Custom Domains, information about the Certificate, but there is no method to upload a new one or change it with a new one. I can only modify the information of an actual one like Expiry date, thumbprint etc.

var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud);
var apiManagementClient = new ApiManagementClient(credentials) { SubscriptionId = subscriptionId };
var certificateClient = new CertificateClient(new Uri(KeyVaultUrl), new DefaultAzureCredential());
var certificate = await certificateClient.GetCertificateAsync(certificateName);
var apiManagementService = await apiManagementClient.ApiManagementService.GetAsync(
                 resourceGroupName,
                 serviceName);
var certificateList = apiManagementClient.Certificate.ListByService(resourceGroupName, serviceName);
var certificateExpiryDate = certificateList.FirstOrDefault(l=>l.Name.Equals(certificateName)).ExpirationDate;
var certificateThumbprint = certificateList.FirstOrDefault(l => l.Name.Equals(certificateName)).Thumbprint;
var certificateInformation = new CertificateInformation
            {
                Expiry = certificateExpiryDate,
                Subject = "",
                Thumbprint = certificateName,
            };
var customDomain = apiManagementService.HostnameConfigurations.FirstOrDefault(v => v.CertificateSource.Equals("KeyVault"));
customDomain.Certificate = certificateInformation;

Solution

  • You can update APIM service hostname configuration via UpdateWithHttpMessagesAsync operation. Pass your custom hostname information in HostnameConfigurations property.

    Type property specifies for what endpoint in APIM you want custom domain.

    CertificateSource property specifies where certificate is coming from:

    • Managed - certificate is provided by APIM itself. It's more complicated as you need to prove domain name ownership. See: Managed Certificate support for Azure API Management
    • KeyVault - certificate should be taken by APIM from KeyVault you provide. Make sure APIM identity has access to key vault and specify: KeyVaultId, and possibly IdentityClientId
    • Custom - your own custom SSL certificate. Specify: EncodedCertificate and CertificatePassword
    • BuiltIn - says to use APIM's built in certificates, can only be used with APIM's default domain names.