問題
Dataverse APIを呼び出す時、アクセストークンの取得は必要があります。
MS認証を実装したら、いつもAADSTS50076エラーを返してきます。
エラーを確認すると、二重認証でアクセストークンが取得できませんっていうことです。
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 '00000001-0000-0000-c000-000000000000'.
解決方法
あるアカウントの二重認証を外して、かつ、管理者権限を付与する。そのアカウントでアクセストークンを取得します。
サンプルコード
※XXXXXXXは自分の情報を入れてください
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Net.Http;
using System;
using static System.Console;
namespace ConsoleApp2
{
class testClass
{
/// <summary>
/// Holds the Authentication context based on the Authentication URL
/// </summary>
static AuthenticationContext authContext;
/// <summary>
/// Holds the actual authentication token once after successful authentication
/// </summary>
static AuthenticationResult authToken;
static string apiUrl = "https://XXXXX.api.crm.dynamics.com/api/data/v9.2";
/// <summary>
/// Client ID or Application ID of the App registration in Azure
/// </summary>
static string clientId = "XXXXXXXXXXX";
/// <summary>
/// The Redirect URL which we defined during the App Registration
/// </summary>
static string redirectUrl = "http://localhost/";
static string userId = "XXXX@XXXX.onmicrosoft.com";
static string password = "XXXXXXXX";
public static async void GetToken()
{
AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(apiUrl)).Result;
string resourceUrl = ap.Resource;
string authorityUrl = ap.Authority;
authContext = new AuthenticationContext(authorityUrl, false);
UserCredential credentials =
new UserPasswordCredential(userId, password);
//Genertae the AuthToken by using Credentials object.
authToken = await authContext.AcquireTokenAsync
(resourceUrl, clientId, credentials);
WriteLine("Got the authentication token, Getting data from Webapi !!");
GetData(authToken.AccessToken);
}
public static async void GetData(string token)
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes time out period.
// Pass the Bearer token as part of request headers.
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
var data = await httpClient.GetAsync("https://XXXXXXX.api.crm.dynamics.com/api/data/v9.2/accounts?$select=name");
if (data.StatusCode == System.Net.HttpStatusCode.OK)
{
WriteLine(await data.Content.ReadAsStringAsync());
JObject body = JObject.Parse(
data.Content.ReadAsStringAsync().Result);
Console.WriteLine(body);
}
else
{
WriteLine($"Some thing went wrong with the data retrieval. Error code : {data.StatusCode} ");
}
ReadLine();
}
}
}
}
ソース実行結果
注意点
取得結果が空の場合は、アカウントを管理者権限が付与されていない可能性があります。