Tuesday, July 26, 2022

How to authenticate your application from azure active directory to perform operations on Dynamics 365.


There are two main ways to authenticate your application
1.      Using username and Password
2.      Using app/client id and secret key
For this mail we use  2nd method to authenticate an application
login in to your azure account, register you application ND mark down the following attributes.
 Once you login go to azure active directory on left pane
and under that App registration section




1- Create a new app registration on top nevbar of app registration enter the name of application, select Web app/API, enter sign on URL (hosted application URL)
 2- Note THE Application ID of the new created application
 3- Go to Endpoints note the key after base URL (this is application tenant)

4- open the newly created application->go to settings->Keys-> create a new (value will be called Secret key)


Now we are done with azure part.
 Create a new console application
1- Include the following references
 2-   create a new class ClientConfiguration
public class ClientConfiguration
{
public static ClientConfiguration Default { get { return ClientConfiguration.OneBox; } }

public static ClientConfiguration OneBox = new ClientConfiguration()
{
UserName = “your account username”,
// Insert the correct password here for the actual test.
Password = “Password of azure account”,

ActiveDirectoryResource = “https://usnconeboxax1aos.cloud.onebox.dynamics.com”,
ActiveDirectoryClientAppId = “explain in point 3”,
// Insert here the application secret when authenticate with AAD by the application
ActiveDirectoryClientAppSecret = “explain in point 5”,

// Change TLS version of HTTP request from the client here
// Ex: TLSVersion = “1.2”
// Leave it empty if want to use the default version
TLSVersion = “”,
};

public string TLSVersion { get; set; }
public string UriString { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string ActiveDirectoryResource { get; set; }
public String ActiveDirectoryTenant { get; set; }
public String ActiveDirectoryClientAppId { get; set; }
public string ActiveDirectoryClientAppSecret { get; set; }
}
You can get the code from Microsoft documentation
Create new Class OAuthHelper
public class OAuthHelper
{
/// <summary>
/// The header to use for OAuth authentication.
/// </summary>
public const string OAuthHeader = “Authorization”;

/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
/// <returns>The authentication header for the Web API call.</returns>
public static string GetAuthenticationHeader(bool useWebAppAuthentication = false)
{
string aadTenant = ClientConfiguration.Default.ActiveDirectoryTenant;
string aadClientAppId = ClientConfiguration.Default.ActiveDirectoryClientAppId;
string aadClientAppSecret = ClientConfiguration.Default.ActiveDirectoryClientAppSecret;
string aadResource = ClientConfiguration.Default.ActiveDirectoryResource;

AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant, false);
AuthenticationResult authenticationResult;

if (string.IsNullOrEmpty(aadClientAppSecret))
{
Console.WriteLine(“Please fill AAD application secret in ClientConfiguration if you choose authentication by the application.”);
throw new Exception(“Failed OAuth by empty application secret.”);
}

try
{
// OAuth through application by application id and application secret.
var creadential = new ClientCredential(aadClientAppId, aadClientAppSecret);
authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
}
catch (Exception ex)
{
Console.WriteLine(string.Format(“Failed to authenticate with AAD by application with exception {0} and the stack trace {1}”, ex.ToString(), ex.StackTrace));
throw new Exception(“Failed to authenticate with AAD by application.”);
}

return authenticationResult.CreateAuthorizationHeader();
}
1.      }

On program.cs
Write the following code
string GetUserSessionOperationPath = string.Format(“{0}{1}”, ClientConfiguration.Default.UriString.TrimEnd(‘/’), sessionUrl);

var request = HttpWebRequest.Create(GetUserSessionOperationPath);
request.Headers[OAuthHelper.OAuthHeader] = OAuthHelper.GetAuthenticationHeader(true);
request.Method = “POST”;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();

Note on request.header we are calling the get authentication header which gets the attribute from client configuration class and on success it will add a token on header
now you can do the rest.
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(bytestring, 0, bytestring.Length);
}

using (var response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
string responseString = streamReader.ReadToEnd();

Console.WriteLine(responseString);
}
}
}
 

No comments:

Post a Comment

if you have any doubts, please tell me

More Than One Form Was Opened at Once for the Lookup Control

In Dynamics 365 for Finance and Operations, when subscribing to a lookup event to modify an existing lookup on a form control, you must...