0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Dynamics CRM APIログイン画面なしで、データを取得するサンプル

Last updated at Posted at 2022-11-04

問題

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'.

解決方法

あるアカウントの二重認証を外して、かつ、管理者権限を付与する。そのアカウントでアクセストークンを取得します。
image.png

サンプルコード

※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();
            }
        }

    }

}

ソース実行結果

image.png

注意点

取得結果が空の場合は、アカウントを管理者権限が付与されていない可能性があります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?