Generic OAuth2 Library for Business Central

Generic OAuth2 Library for Business Central is to acquire Access Token from Azure AD, Google, Facebook etc. OAuth is most commonly used authorization method across all platforms. Acquiring Access Token is a little difficult in Business Central, though there is a Codeunit called OAuth2 available in the system. To help the Business Central developers' community, I thought of creating this generic library for OAuth2, so that developers can use this in their applications.


Supported Types

The following grant types are supported:

  • Authorization Code

  • Tested with Azure AD, Google, Facebook

  • Password Credentials

  • Tested with Azure AD

  • Client Credentials

  • Not yet tested

Please refer oauth.net to understand OAuth and grant types.


Setup OAuth 2.0 Applications

First you need to setup a client application in the provider's website.

example: portal.azure.com, console.developers.google.com, developers.facebook.com/apps etc.


Note: Please refer to the Graph API post to learn how to register and setup an application in azure portal.


OAuth 2.0 Application (Page 50101)

Client ID, Client Secret, Scope / Permissions, Endpoints etc. inputs need to be updated in this page. Most of the inputs are available in the application that you have registered in the provider's website.


You can test the configuration by clicking on the "Request Access Token" action button.


OAuth 2.0 Applications (Page 50100)

You can see list of Applications with the status. Using this, you can create a new application.



How to Use

After updating the application details in "OAuth 2.0 Application" page, you can use the following Codeunit to get Access Token.


OAuth 2.0 App. Helper (Codeunit 50101)


RequestAccessToken method will update Access Token in "OAuth 2.0 Application" record. It will return false with an error message if it is failed.


The following code acquires access token from Google and displays in a message box.

procedure GetGoogleAccessToken()
var
	OAuth20Appln: Record "OAuth 2.0 Application";
	OAuth20AppHelper: Codeunit "OAuth 2.0 App. Helper";
	MessageText: Text;
begin
	OAuth20Appln.Get('GOOGLE');
	if not OAuth20AppHelper.RequestAccessToken(OAuth20Appln, MessageText) then
		Error(MessageText);

	Message('%1', OAuth20AppHelper.GetAccessToken(OAuth20Appln));
end;


Conclusion

You can download and use these objects in your application. But I recommend testing all integration scenarios thoroughly before using in production environment. If you have any questions you can ask by writing comments below this post.


Code in Action

Access Token from Facebook:


You can download the complete source code from GitHub, and you can report issues on GitHub Issue Tracker.


#MsDyn365 #MsDyn365BC #BusinessCentral #DynamicsNAV #OAuth2

2,258 views5 comments

© 2020 by msnJournals.com

  • Facebook Social Icon
  • LinkedIn Social Icon
  • Twitter Social Icon
  • GitHub-Mark-120px-plus