Implementing OAuth Authentication with Microsoft Online API using X++

In this blog post, we’ll walk through how to interact with Microsoft Online API for OAuth authentication in a Microsoft Dynamics AX environment using X++ code. OAuth authentication is commonly used for secure API access, and this method enables your application to request an access token from Microsoft’s OAuth endpoint for authentication.

This process is particularly useful when you need to integrate Dynamics AX or Dynamics 365 with external applications or services, such as Microsoft Graph or other cloud-based APIs. We’ll use a simple scenario to demonstrate how you can authenticate using the client_credentials grant type and acquire an access token.

1.Prerequisites:

Before diving into the code, ensure you have the following prerequisites:

  1. Azure Active Directory (AAD): You must have an Azure AD app registered to use client credentials for OAuth authentication. This gives you a client_id and client_secret.
  2. X++ Development Environment: Access to a development environment in Dynamics AX or Dynamics 365 Finance and Operations (D365FO).

    2.Code Breakdown:

    Let’s go step by step through the code.

    System.Net.HttpWebRequest webRequest;
    System.Net.HttpWebResponse webResponse;
    System.IO.Stream stream;
    System.IO.StreamReader streamReader;
    System.Byte[] bytes;
    System.String ResponseStr;
    System.Net.WebHeaderCollection headers;
    str response = '';
    System.Text.UTF8Encoding encoding;
    str body;
    str boundary;
    str formData;
    str newLine;

    Here, we start by defining various variables that we’ll use later, including the webRequest and webResponse for handling the HTTP communication, a Stream to read the response, and a StreamReader to process the response content.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

    3.Request Setup:

    Before diving into the code, ensure you have the following prerequisites:

    1. new InteropPermission(InteropKind::ClrInterop).assert();

      This line asserts the required permissions for the CLR interop, allowing us to use .NET libraries in X++. Without this, the interop to external .NET assemblies would fail.

      webRequest = System.Net.WebRequest::Create('https://login.microsoftonline.com/TenantId/oauth2/token') as System.Net.HttpWebRequest;

      This creates a HttpWebRequest to the Microsoft OAuth2 endpoint, where we will request an authentication token.

    4.Configuring Headers and Content Type:

    headers = new System.Net.WebHeaderCollection();
    webRequest.set_Headers(headers);
    webRequest.set_Method('POST');

    Here, we are preparing the headers for the request. This is a POST request because we will be sending form data to request the token.

    webRequest.set_ContentType('application/x-www-form-urlencoded');

    We set the content type to application/x-www-form-urlencoded as that is the format required for the POST request when sending form data.

    5.Creating Form Data:

    newLine = "\r\n";
    formData = "grant_type=client_credentials&"
    + "client_id=CLIENT_ID"
    + "client_secret=CLIENT_SECRET"
    + "resource=EnvironmentURL";

    The formData string is constructed with the necessary parameters:

    • grant_type=client_credentials: This specifies the client credentials flow.
    • client_id and client_secret: These are the credentials for your Azure Active Directory application.
    • resource: The resource URL for your Dynamics 365 environment (the API you want to access).

    6.Sending the Request:

    encoding = new System.Text.UTF8Encoding();
    bytes = encoding.GetBytes(formData);
    webRequest.set_ContentLength(bytes.get_Length());

    Here, we encode the form data as bytes and set the Content-Length header accordingly.

    stream = webRequest.GetRequestStream();
    stream.Write(bytes, 0, bytes.get_Length());
    stream.Close();

    We get the request stream, write the bytes to it, and then close it to complete the request body.

    7.Handling the Response:

    webResponse = webRequest.GetResponse();
    stream = webResponse.GetResponseStream();
    streamReader = new System.IO.StreamReader(stream);
    response = streamReader.ReadToEnd();
    info(strFmt("response -> %1", response));

    Once the request is sent, we read the response from the Microsoft OAuth endpoint. The response is typically a JSON object containing an access token, which you can then use for subsequent API calls.

    8.Clean-Up:

    streamReader.Close();
    stream.Close();

    Finally, we clean up the streams to ensure proper resource management.

    Conclusion:

    In this example, we’ve demonstrated how to make an HTTP request in X++ to authenticate with Microsoft’s OAuth2 endpoint. By using the client_credentials flow, you can securely request an access token for your applications to interact with Microsoft APIs such as Dynamics 365.

    This is just a starting point. You can extend this implementation to handle errors, manage token expiration, or integrate it with your business logic in Dynamics AX/D365FO. Secure integration with external systems via OAuth authentication is an essential part of modern cloud-based applications and offers a powerful method for extending the functionality of your Dynamics environment.

    Improved 365 Team