a3

In this tutorial i will explain how to authenticate your application from azure active directory to perform operations on Dynamics 365.

So there are ways to authenticate your application

  1. Using username and Password
  2. Using app/client id and secret key

For this tutorial I will be explain 2nd method to authenticate your application

Before proceeding to code, first login in to your azure account, register you application mark down following attributes.

 

  1. Once you login go to azure active directory on left pane
    and under that App registration section
    a3
  2. 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)
    a1
  3. Note Application ID of the new created application
    a4
  4. Go to Endpoints note the key after base URL (this is application tenant)a5a6
  5. Now open new created application->go to settings->Keys-> create a new (value will be called Secret key)
    a7 a2

Now we are done with azure part.

 

  1. Create a new console application
  2. Include the following references
    a9
  3. create a new class ClientConfiguration

public class ClientConfiguration

{

public static ClientConfiguration Default { get { return ClientConfiguration.OneBox; } }

 

public static ClientConfiguration OneBox = new ClientConfiguration()

{

UriString = “https://usnconeboxax1aos.cloud.onebox.dynamics.com/”,

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”,

ActiveDirectoryTenant = “https://login.windows.net/tenant key (explain in point 4)/”,

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);

}

}

}

 

 

Leave a Reply

Recent Comments

    Archives

    Categories