Manage Azure with C# .Net 5 - Add Custom Domain and App Service Managed Certificate to Azure App Service

David Warwick 121 Reputation points
2022-01-16T19:45:10.237+00:00

Hello all. I am following a sample from https://github.com/davidebbo/AzureWebsitesSamples

private static ResourceManagementClient _resourceGroupClient;  
private static WebSiteManagementClient _websiteClient;  
private static AzureEnvironment _environment;  
private static DnsManagementClient _dnsClient;  
  
static string _ClientId = Startup.StaticConfig.GetValue<string>("Azure:ClientId");  
static string _ClientKey = Startup.StaticConfig.GetValue<string>("Azure:ClientSecret");  
static string _TenantId = Startup.StaticConfig.GetValue<string>("Azure:TenantId");  
static string _SubscriptionId = Startup.StaticConfig.GetValue<string>("Azure:SubscriptionId");  
static string _ResourceGroupName = Startup.StaticConfig.GetValue<string>("Azure:ResourceGroupName");  
static string _AppName = Startup.StaticConfig.GetValue<string>("Azure:AppName");  
  
public static string ResourceGroupName { get => _ResourceGroupName; set => _ResourceGroupName = value; }  
  
public static async Task MainAsync()  
{  
    // Set Environment - Choose between Azure public cloud, china cloud and US govt. cloud  
    _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];  
  
    // Get the credentials  
    TokenCloudCredentials cloudCreds = await GetCredsFromServicePrincipal();  
  
    var tokenCreds = new TokenCredentials(cloudCreds.Token);  
  
    //var loggingHandler = new LoggingHandler(new HttpClientHandler());  
  
    // Create our own HttpClient so we can do logging  
    var httpClient = new HttpClient();  
  
    // Use the creds to create the clients we need  
    _resourceGroupClient = new ResourceManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds );  
    _resourceGroupClient.SubscriptionId = cloudCreds.SubscriptionId;  
    _websiteClient = new WebSiteManagementClient(_environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager), tokenCreds);  
    _websiteClient.SubscriptionId = cloudCreds.SubscriptionId;  
    _dnsClient = new DnsManagementClient(tokenCreds);  
  
    AddCustomDomainToSite("mycustomdomain.com");  
  
      
}  
  
private static async Task<TokenCloudCredentials> GetCredsFromServicePrincipal()  
{  
    // Quick check to make sure we're not running with the default app.config  
    if (_SubscriptionId[0] == '[')  
    {  
        throw new Exception("You need to enter your appSettings in app.config to run this sample");  
    }  
  
    var authority = String.Format("{0}{1}", _environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory], _TenantId);  
    var authContext = new AuthenticationContext(authority);  
    var credential = new ClientCredential(_ClientId, _ClientKey);  
    var authResult = await authContext.AcquireTokenAsync(_environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId], credential);  
    return new TokenCloudCredentials(_SubscriptionId, authResult.AccessToken);  
}  
  
  
static void AddCustomDomainToSite(string sDomainName)  
{  
  
    Domain domain = new Domain();  
  
    _websiteClient.Domains.CreateOrUpdateAsync(_ResourceGroupName, "mycustomdomain.com", domain);  
}  
  

I am trying to add mycustomdomain.com to my Azure app service. When I execute the code _websiteClient.Domains.CreateOrUpdateAsync(_ResourceGroupName, "mycustomdomain.com", domain);, nothing happens. I do not get any errors, and I do not see the custom domain listed under Custom Domains in my app service.

I have already verified ownership of the domain, and I can add it to my app service via the portal, but I am trying to add it through C#. Can someone please help me?

Edit: Updated post

I am now using the code below:

static string _ClientId = Startup.StaticConfig.GetValue<string>("Azure:ClientId");  
        static string _ClientKey = Startup.StaticConfig.GetValue<string>("Azure:ClientSecret");  
        static string _TenantId = Startup.StaticConfig.GetValue<string>("Azure:TenantId");  
        static string _SubscriptionId = Startup.StaticConfig.GetValue<string>("Azure:SubscriptionId");  
        static string _ResourceGroupName = Startup.StaticConfig.GetValue<string>("Azure:ResourceGroupName");  
        static string _AppName = Startup.StaticConfig.GetValue<string>("Azure:AppName");  
  
        public static async Task<HttpStatusCode> AddHostNameFromForumResponse(string sHostName)  
        {  
            var appId = _ClientId;  
            var secretKey = _ClientKey;  
            var tenantId = _TenantId;  
            var context = new AuthenticationContext("https://login.windows.net/" + tenantId);  
            ClientCredential clientCredential = new ClientCredential(appId, secretKey);  
            var tokenResponse = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result;  
            var accessToken = tokenResponse.AccessToken;  
            using (var client = new HttpClient())  
            {  
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);  
                var baseUrl = new Uri($"https://management.azure.com/");  
                var requestURl = baseUrl + $"subscriptions/{_SubscriptionId}/resourceGroups/{_ResourceGroupName}/providers/Microsoft.Web/sites/{_AppName}/hostNameBindings/{sHostName}?api-version=2016-08-01";  
                string body = $"{{\"properties\": {{\"azureResourceName\": \"{_AppName}\"}}}}";  
                var stringContent = new StringContent(body, Encoding.UTF8, "application/json");  
                var response = await client.PutAsync(requestURl, stringContent);  
  
                return response.StatusCode;  
            }  
  
        }  

I am getting a response status code of Forbidden. I think I do not have my permissions set-up correctly according to https://stackoverflow.com/a/52051578/1561777

When I go to my app service, I see:

166574-image.png

Then if I try to add an owner to my app, registered in Active Directory, I see:

166499-image.png

I notice in the post on Stack Overflow, I do not see "Azure AD User, Group, or Application". So I think I do not have my app properly registered with Active Directory.

This is what I see in Active Directory:

166500-image.png

Notice that my app is registered in Active Directory. Not sure what I am missing. Any ideas?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,237 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,026 questions
{count} votes

Accepted answer
  1. MughundhanRaveendran-MSFT 12,441 Reputation points
    2022-02-01T09:14:51.32+00:00

    @David Warwick ,

    I am summarizing the discussions that were made in the comments and providing it as an answer so that it helps the community.

    The code sample that you were initially refering was legacy code. I suggested you to use the Rest Api to add custom domains : https://learn.microsoft.com/en-us/rest/api/appservice/web-apps/create-or-update-host-name-binding . Also it would work for a domain that is hosted in GoDaddy as it is a trusted provider.

    There were some authorization issues after adding the domain but it got resolved after following this article : https://learn.microsoft.com/en-in/azure/active-directory/develop/howto-create-service-principal-portal

    This article was refered to add a managed certificate to the custom domain.


0 additional answers

Sort by: Most helpful