Обновление класса для использования MFA для доступа к Dynamics 365 - PullRequest
0 голосов
/ 24 февраля 2020

Системный администратор включил 2FA, поэтому мне нужно go просмотреть и обновить некоторые программы, чтобы использовать его для доступа к API-интерфейсу Dynamics. В противном случае мы получили следующее:

{ 

   "error":"interaction_required",
   "error_description":"AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000007-0000-0000-c000-000000000000'.\r\nTrace ID: 24822bc6-9e93-476d-8580-fd04e3889300\r\nCorrelation ID: efd5dbc5-dead-4665-a5a6-570ae15a55fb\r\nTimestamp: 2020-02-24 20:35:15Z",
   "error_codes":[ 

      50076
   ],
   "timestamp":"2020-02-24 20:35:15Z",
   "trace_id":"24822bc6-9e93-476d-8580-fd04e3889300",
   "correlation_id":"efd5dbc5-dead-4665-a5a6-570ae15a55fb",
   "error_uri":"https://login.windows.net/error?code=50076",
   "suberror":"basic_action"
}

В этой статье это звучит довольно просто и представляет собой процесс, который нам пришлось использовать для Outlook и других приложений. В основном, генерация пароля приложения.

Однако я пытаюсь использовать пароль приложения вместо пароля по умолчанию, который мы использовали некоторое время, и все еще не могу получить токен доступа для программы.

Вот что мы использовали:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace CrmQbInvoiceSync
{
  class CrmAuthorization
  {

    // Serialize the JSON response for the access_token
    public class AccessToken
    {
      public string access_token { get; set; }
    }

    public static async Task<string> GetCrmAccessToken()
    {
      var values = new Dictionary<string, string>
      {
        // Connection parameters
        {"client_id", ConfigurationManager.AppSettings["clientId"]},
        {"client_secret", ConfigurationManager.AppSettings["clientSecret"]},
        {"resource", ConfigurationManager.AppSettings["crmOrg"]},
        {"username", ConfigurationManager.AppSettings["username"]},
        {"password", ConfigurationManager.AppSettings["userPassword"]},
        {"grant_type", "password"}
      };

      // Console.WriteLine(values);

      // Convert to x-www-form-urlencoded
      var content = new FormUrlEncodedContent(values);
      try
      {
        // Send the x-www-form-urlencoded info to the OAuth2 end point
        HttpResponseMessage response = await Services.Client.PostAsync(ConfigurationManager.AppSettings["crmUri"], content);
        // Get the body from the response
        var responseContent = await response.Content.ReadAsStringAsync();

        // Extract out the access token from the response
        AccessToken responseBody = JsonConvert.DeserializeObject<AccessToken>(responseContent);

        // Test if there is an access token present
        if (responseBody.access_token != null)
        {
          // If there is an access token, take it and use it in
          // generating the query
          var accessToken = responseBody.access_token;
          return accessToken;
        }
        else
        {
          var accessToken = "Could not get the access token.";
          Services.WriteLogFile(accessToken);
          Console.WriteLine(accessToken);
          return null;
        }

      }
      catch (Exception e)
      {
        var error = e;
        Services.WriteLogFile(error.ToString());
        Console.WriteLine(error);
        throw;
      }
    }
  }
}

На строку {"password", ConfigurationManager.AppSettings["userPassword"]} следует обратить внимание, поэтому я обновил AppSettings новым паролем приложения. Получите эту ошибку, но похоже, что она должна работать, если я использую пароль приложения:

Formatted JSON Data
{ 

   "error":"invalid_grant",
   "error_description":"AADSTS50126: Error validating credentials due to invalid username or password.\r\nTrace ID: 17bf1365-32a0-439e-bd99-9eaf8e3bab00\r\nCorrelation ID: 4d24cac1-dae9-49b7-961f-c7c739f885f4\r\nTimestamp: 2020-02-24 20:33:43Z",
   "error_codes":[ 

      50126
   ],
   "timestamp":"2020-02-24 20:33:43Z",
   "trace_id":"17bf1365-32a0-439e-bd99-9eaf8e3bab00",
   "correlation_id":"4d24cac1-dae9-49b7-961f-c7c739f885f4",
   "error_uri":"https://login.windows.net/error?code=50126"
}

Действительно, я не уверен, что мне следует обновлять что-то еще в программе, чтобы приспособить MFA, но статьи I прочитал, указывают, что я должен просто генерировать пароль приложения, и это должно быть хорошо. Предложения

1 Ответ

0 голосов
/ 26 февраля 2020

Я предлагаю вам использовать токен refre sh, чтобы обновить sh токен доступа . Используя refre sh token, вы можете обойти это ограничение MFA.

Для получения токена refre sh необходимо выполнить Azure поток кода аутентификации OAuth2 AD , чтобы интерактивно получить токен refre sh. И тогда вы можете получить новый токен с полученным вами токеном refre sh.

Обратите внимание, что токен refre sh должен храниться в секрете. Если это было скомпрометировано, вы можете отозвать все refre sh токены определенного c использования с PowerShell Revoke-AzureADUserAllRefreshToken

...