Take a look at the Authorization Helper, which is part of the sample console app provided by Microsoft for the data management api (see the last sentence in https://learn.microsoft.com/en-us/dynamics365/fin-ops-core/dev-itpro/data-entities/data-management-api). The Program.cs of the app shows how the Authentication Helper is used.
AuthorizationHelper.cs
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AuthorizationHelper
{
public class AuthorizationHelper
{
const string aadTenant = "https://login.windows.net/<your-tenant>";
public const string aadResource = "https://<yourAOS>.cloudax.dynamics.com";
const string aadClientAppId = "<client id>";
const string aadClientAppSecret = "<client secret>";
/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
/// <returns>The authentication header for the Web API call.</returns>
public static string GetAuthenticationHeader()
{
AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant);
AuthenticationResult authenticationResult;
var creadential = new ClientCredential(aadClientAppId, aadClientAppSecret);
authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
// Create and get JWT token
return authenticationResult.CreateAuthorizationHeader();
}
}
}
Program.cs
using ODataClient.Microsoft.Dynamics.DataEntities;
using System;
namespace DataPackageHandler
{
using AuthorizationHelper;
using Microsoft.OData.Client;
class Program
{
static void Main(string[] args)
{
string ODataEntityPath = AuthorizationHelper.aadResource + "/data";
Uri oDataUri = new Uri(ODataEntityPath, UriKind.Absolute);
var d365Client = new Resources(oDataUri);
d365Client.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(delegate (object sender, SendingRequest2EventArgs e)
{
var authenticationHeader = AuthorizationHelper.GetAuthenticationHeader();
e.RequestMessage.SetHeader("Authorization", authenticationHeader);
});
PackageImporter.ImportPackage(d365Client, @"..\debug\SampleData\usmf_asset-major-types-01.zip");
PackageExporter.ExportPackage(d365Client, @"..\debug\SampleData\");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}