Search code examples
azureazure-management-api

Azure API failed to authenticate the request


I am using the next code to get the token for Azure AD authentication

errorMessage = "";
        AuthenticationResult result = null;
        var context = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["login"], ConfigurationManager.AppSettings["tenantId"]),false);
        ClientCredential clientCredential = new ClientCredential(ConfigurationManager.AppSettings["clientId"], ConfigurationManager.AppSettings["key"]);
        try
        {
            result = context.AcquireToken(ConfigurationManager.AppSettings["apiEndpoint"], clientCredential);
        }
        catch (AdalException ex)
        {
            if (ex.ErrorCode == "temporarily_unavailable")
            {
                errorMessage = "Temporarily Unavailable";
                return null;
            }
            else
            {
                errorMessage = "Unknown Error";
                return null;
            }
        }
        string token = result.AccessToken;
        var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"],token);
        //string certificateString = ConfigurationManager.AppSettings["managementCertificate"];
        //var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
        return credential;

After that I am doing the next to create a website in Azure

            using (var computeClient = new WebSiteManagementClient(credentials))
        {
            var result = computeClient.WebSites.IsHostnameAvailable(websiteName);
            if (result.IsAvailable)
            {
                await computeClient.WebSites.CreateAsync(WebSpaceNames.WestEuropeWebSpace, new WebSiteCreateParameters() {
                    Name= websiteName,
                    ServerFarm= ConfigurationManager.AppSettings["servicePlanName"]
                });
            }
            else
            {
                return ResultCodes.ObjectNameAlreadyUsed;
            }
        }

But every time I execute that I got the following error:

ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.

I tried to import the management certificate as they said here: https://www.simple-talk.com/cloud/security-and-compliance/windows-azure-management-certificates/

And also tried this one: http://technetlibrary.com/change-windows-azure-subscription-azure-powershell/198

For importing management certificate.
Also I gave the application permissions to access management API.


Solution

  • Azure AD Authentication DOES NOT use the management certificate authentication.

    There is a good documentation and code sample on MSDN on how to resolve your current issue. Authenticating Service Management Requests