API-интерфейс Azure Mysql HTTP REST. Получить JSON Web Token

0

Я пытаюсь подключиться к своему Azure Mysql через http rest api (https://docs.microsoft.com/en-us/rest/api/mysql/) без успеха. Проблема в том, что я не могу получить JSON Web Token из своего веб-приложения. Ситуация:

Azure Web App ----- rest api → Azure MySql

Думаю, мне нужно "зарегистрировать" этот ресурс сервера Mysql в активном каталоге, но, похоже, я не могу этого сделать.

Я выполнил этот учебник (https://blogs.msdn.microsoft.com/jpsanders/2017/03/17/accessing-azure-app-services-using-azure-ad-bearer-token-2), но у меня есть тот же Проблема: я не могу зарегистрировать MySql в Azure Active Directory.

Итак, как я могу получить JSON Web Token для Mysql HTTP REST API?

Спасибо!

-------- AD PROPIETARY ROLE ДЛЯ MYSQL RESOURCE (НЕ СЕРВЕР MYSQL) - Изображение 174551 ---------------- КОД --------- -------------------------------------

    //
// 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); }

--------------- ПОСЛЕ ИЗМЕНЕНИЙ СЕЙЧАС ПОЛУЧЕНИЕ НЕСАНКЦИОНИРОВАННЫХ ---------------

Изображение 174551

  • 0
    Похоже, что этот API предназначен для управления базами данных Azure MySQL, их создания и т. Д. Если вам нужно подключиться к базе данных MySQL, я думаю, что вам следует установить соединение с именем пользователя + паролем на сервере MySQL, как обычно.
  • 0
    Спасибо, но мне нужно соединиться с остальным API для обновления правил брандмауэра Mysql из веб-приложения.
Показать ещё 16 комментариев
Теги:
azure
rest
http

1 ответ

0

Я комментирую важные моменты нашей дискуссии в комментариях, которые привели к решению:

  • Используйте https://management.azure.com в качестве идентификатора resource при приобретении токена доступа
  • Используйте https://login.microsoftonline.com/tenant-id-here/ в качестве полномочий (вы также можете использовать проверенное имя домена вместо id). Это определяет, какой арендатор AAD вы аутентифицируете
  • Маркер доступа должен быть присоединен с new AuthenticationHeaderValue("Bearer", token.AccessToken) на С#, так что результирующий заголовок является Authorization: Bearer tokengoeshere
  • Наконец, убедитесь, что вы предоставили разрешения для правильного приложения. Могут быть приложения с одинаковым или похожим именем.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню