0
votes

I'm trying to connect to my Azure Mysql via http rest api (https://docs.microsoft.com/en-us/rest/api/mysql/) without success. The problem is that i can't get the JSON Web Token from my Web App. Situation:

Azure Web App ----- rest api ----> Azure MySql

I guess i need to 'register' this Mysql Server resource in active directory but seems i can't do it.

I followed this tutorial (https://blogs.msdn.microsoft.com/jpsanders/2017/03/17/accessing-azure-app-services-using-azure-ad-bearer-token-2) but i have the same problem : i can't register MySql in Azure Active Directory .

So, how can i obtain a JSON Web Token for Mysql HTTP REST API ?

Thanks!

-------- AD PROPIETARY ROLE FOR MYSQL RESOURCE (NOT MYSQL SERVER) -- enter image description here ---------------- CODE ----------------------------------------------

    //
// https://blogs.msdn.microsoft.com/jpsanders/2017/03/17/accessing-azure-app-services-using-azure-ad-bearer-token-2/
//
public static class AzureActiveDirectory
{
    // the AD Authority used for login.  For example: https://login.microsoftonline.com/myadnamehere.onmicrosoft.com 
    public static string authority = "";
    // the Application ID of this app.  This is a guid you can get from the Advanced Settings of your Auth setup in the portal
    public static string clientId = "";
    // the key you generate in Azure Active Directory for this application
    public static string clientSecret = "";
    // the Application ID of the app you are going to call.This is a guid you can get from the Advanced Settings of your Auth setup for the targetapp in the portal
    public static string resource = "";


    static public async Task<AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
    {
        var task =  await GetS2SAccessToken(authority, resource, clientId, clientSecret);
        return task;
    }

    static async Task<AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
    {
        var clientCredential = new ClientCredential(clientId, clientSecret); 
        AuthenticationContext context = new AuthenticationContext(authority, false); 
        AuthenticationResult authenticationResult = await context.AcquireTokenAsync(
            resource,  // the resource (app) we are going to access with the token
            clientCredential);  // the client credentials
        return authenticationResult; 
    }

}





  AzureActiveDirectory.authority = "https://login.microsoftonline.com/********/";
        AzureActiveDirectory.clientId = "********";                                             
        AzureActiveDirectory.clientSecret = "********";
        AzureActiveDirectory.resource = "https://management.azure.com/";

        try
        {


            AuthenticationResult token = await AzureActiveDirectory.GetS2SAccessTokenForProdMSAAsync();

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + token.AccessToken);
            var resp = await client.GetAsync("https://management.azure.com/subscriptions/*******/resourceGroups/MYSQL/providers/Microsoft.DBforMySQL/servers/shoplister/firewallRules?api-version=2017-12-01");

            Console.WriteLine(resp.StatusCode.ToString());
            Console.WriteLine();

        }
        catch (Exception e) { Console.WriteLine(e); }

--------------- AFTER CHANGES NOW GETTING UNAUTHORIZED ------------

enter image description here

1
Ahh okay. Then you'll need to register the app in Azure AD and assign the app a role on the mysql resource. Then you can acquire access tokens to call the API from Azure AD using client credentials flow. - juunas
Resource URI would be https://management.azure.com/ I believe. It's the identifier for the API you want to call. - juunas
Authority should be https://login.microsoftonline.com/tenant-id-here/ - juunas
I see your problem :) You need to specify the authorization header as new AuthenticationHeaderValue("Bearer", token.AccessToken) - juunas
Hmm, well it's an improvement but not sure why that happens now. You can inspect the access token you get at jwt.ms and check it has the right azure ad tenant id. Also double check that is the same app as what you assigned in Azure portal. Its possible you have given the role to an app with the same name. - juunas

1 Answers

0
votes

I'm compiling the important points from our discussion in the comments that led to a solution:

  • Use https://management.azure.com as the resource identifier when acquiring the access token
  • Use https://login.microsoftonline.com/tenant-id-here/ as the authority (you can also use a verified domain name instead of the id). This defines which AAD tenant you authenticate against
  • The access token must be attached with new AuthenticationHeaderValue("Bearer", token.AccessToken) in C#, so that the resulting header is Authorization: Bearer tokengoeshere
  • Finally make sure you have granted permissions to the right app. There can be apps with an identical or similar name.