How to get Access Token in Business Central using OAuth2 Codeunit

Hello, in view OAuth2 authentication method is currently popular because as of October 1, 2022, it is mandatory to connect to Business Central web services, I wanted to make a post on how to use this authentication method but through the language AL.

The idea of doing it within Business Central, for example, is to be able to connect to the services of another Business Central, additionally, I will also take advantage of the code to show how we could connect to the Graph API with a slight change, directly from Business Central.

Project Overview

Basic concepts

About Graph API

Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources. After you register your app and get authentication tokens for a user or service, you can make requests to the Microsoft Graph API.

https://learn.microsoft.com/en-us/graph/use-the-api

I introduced the concept of API Graph because I want to show how to connect in a very simple way through Oath2.

About Oauth

OAuth is an open standard for authorizing access to web services and APIs from native clients and websites in Azure Active Directory (Azure AD). In Business Central, OAuth is useful when your deployment is configured for Azure Active Directory authentication, either through your own Azure subscription or a Microsoft 365 subscription. OAuth lets users sign in to Business Central web services using their Microsoft 365 or Azure AD credentials.

https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/webservices/authenticate-web-services-using-oauth#about-oauth

As I mentioned at the beginning of the post, Oauth2 is not optional to connect to Business Central services; It is mandatory, so it is essential to know how to configure it.

Some time ago, I made an exclusive post on how to configure Oauth2 to connect to Business Central, there you can find more detailed information on how to create the correct App registration.

Once the App is registered in the Azure portal, we must have the following parameters at hand, which I am going to give a brief explanation of again.

  • Application Client ID: We get this information from the “Application Client Id” of the App Registration.
  • TennatID: We obtain this value from the Directory Tenant ID of the Business Central to which we are going to connect.
  • ClientSecret: We find this value in Certificates & Secrets in the App Registration.
  • RedirectURL: We find this value in Authentication in the App Registration. This should be set to https://businesscentral.dynamics.com/OAuthLanding.htm

To connect to the Graph API you must use this

  • Scope: 'https://graph.microsoft.com/.default'

In the case of wanting to connect to the Business Central API, we must use this:

  • Scope: 'https://api.businesscentral.dynamics.com/.default'

Code in Business Central

This post is completely based on the use of the “Oauth2 native codeunit” to make web service calls from another Business Central within the ERP and, additionally, connect to the API Graph within the ERP.

Codeunits

Constants

I have created this first codeunit for practical purposes to store all the constants that are going to be needed to generate the access token.

GenericApiCalls

The following codeunit allows us to make HTTP requests using the bearer token (Access Token returned by the Oauth2 codeunit) and read the response. This will be used to call Business Central web services and optionally the Graph API

Page

Test OAuth2

The following page has the code to obtain the access token through the Outh2 Codeunit, and additionally the code that makes the use of the Business Central web services call, in this case, we use List companies and the Graph API call.

Obtaining the Token:

For this I have 2 methods GetAccessTokenForGraph and GetAccessTokenForBC, the difference between them is the Scope used.

For GetAccessTokenForGraph the Scope was used: 'https://graph.microsoft.com/.default' and for GetAccessTokenForBC the Scope was used: 'https://api.businesscentral.dynamics.com/.default'

In both methods, the implemented logic is to first call AcquireAuthorizationCodeTokenFromCache method to get the access token from the cache or a refreshed token, in case we don’t get an access token we call AcquireTokenByAuthorizationCode.

Calling the APIs:

Here we have 2 Actions, one to call the Business Central List of Companies (it can be any other web service) and the other to connect to the Graph API.

In both scenarios we make use of the generic codeunit previously presented in the following way:

APICallResponse := GenericApiCalls.CreateRequest(ApitoCall, AccessToken);

Setup in Business Central

For our App Registration to work we must register it in the Azure Active Directory Application within Business Central in order to grant consent.

Note: Consent can only be given by Azure admin user account.

Tests

Next, I will show the use of the actions created, which are the following:

  • Get Token for API Graph: Allows to obtain an access token to be used in the Graph API

The first time, if the token is not cached, it will ask us to use our Business Central user account to provide consent.

Then we will be asked if we agree to give the permissions requested below, which were previously configured in the App Registration in the Azure portal.

Finally, inside the Result Token in the Api Graph, we will obtain the Access Token.

  • Call API Graph: Once the previous step is completed, we can call the Graph API passing in the Bearer Token the one obtained in the previous step.
  • Get Token for API BC:

Similar to getting Token for API Graph, this will be exclusive to be used in Business Central API calls.

Note: If the token is cached, the user authentication windows will not open, but it will directly give us the Access Token.

  • Call API List Companies: Now with the access token for Business Central, we can call the API to obtain companies.

And something similar to the following image should appear.

  • Testing in Postman with the obtained access token: The access token obtained is totally valid to be used in any external application. Although it is not the purpose of this post, because this Oauth2 codeunit would only allow valid tokens to be obtained within Business Central, I want to show that the token would work perfectly for example in Postman

To copy the token, we click on the 3 points of the Access Token of Business Central.

And then in Postman, we use it as Bearer Token and it works perfectly.

Conclusion

Because Oauth2 is mandatory from October 1, 2022, I found it interesting to make a post on how to authenticate with native codeunits with this new mechanism, this scenario would be very useful if we wanted to connect through API, Business Centrals that are in different Tenants or if for example we want to connect to the Graph API for some reason.

Code on GitHub

All the code used in this post can be found at the following link:

Code

For more information, you can visit this interesting Blog or the official documentation of the use of the library exposed in this post.

I hope this has been helpful.

5 thoughts on “How to get Access Token in Business Central using OAuth2 Codeunit

  1. Pingback: How to keep your Keys/values in Business Central using Isolated Storage - Ivan Singleton

  2. BT Reply

    Hi, How do I run this on a job queue, so that the prompt Interaction pop up does not pop up, is this possible to do, I do not want to login as myself each time, it should run through the job queue without a prompt?

Leave a Reply

Your email address will not be published. Required fields are marked *