web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Business Central forum

Business Central API - Authentication with Client ID and Secret

(0) ShareShare
ReportReport
Posted on by

Is it possible to get a valid token from the Business Central API with just the App ID and Secret? Without involving a user prompt/login?

We need to pull data from Business Central without having a user authenticating.

In testing, we've found it to not be possible.

https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-develop-connect-apps#setting-up-azure-active-directory-(aad)-based-authentication

https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code

http://paulryan.com.au/2017/oauth-on-behalf-of-flow-adal/

Are there additional resources which show how to do this?

I have the same question (0)
  • Suggested answer
    Stefano Demiliani Profile Picture
    37,166 Most Valuable Professional on at

    There are two different ways to connect to and authenticate against the APIs.

    1) Use Azure Active Directory (AAD) based authentication against the common API endpoint: api.businesscentral.dynamics.com/.../beta

    2) Use basic authentication with username and password (a so-called web service access key) against the common API endpoint that includes the user domain, for example api.businesscentral.dynamics.com/.../beta.

    I think what you want is method 1.

    However, also method 2 does not require prompting credentials.

    More info here:

    docs.microsoft.com/.../devenv-develop-connect-apps

    For AAD:

    www.cloudfronts.com/explore-business-central-api-through-postman-using-aad-authentication

  • EmilW Profile Picture
    25 on at

    Hi,

    Number 1 that you point to in your answer is the Access code flow and that needs user credentials. I dont see anyway to create the "machine to machine" scenario with that one(i dont want to have a user input from an integration service). I can use number 2 but according to this page: docs.microsoft.com/.../endpoints-apis-for-dynamics i cannot use web service keys in production. This means in my head that the "machine to machine" scenarion cannot be done in production, which feels super strange?

    I really want to use the Client credentials flow(only use app id and secret, send out an admin consent link to the customers IT to approve access etc.) as for e.g. Dynamics 365 Finance and Operations but it seems not to be supported in Business Central? The strange thing is that there are "Application" permissions available when creating the app in Azure Portal so there must be a thought behind it....but there are no guides available as far as what i have found.

    Or did you found another way aherrick?

    Any input or guidance is welcome :-)

  • Community Member Profile Picture
    on at

    Did you solve this?

    I'm trying to use client secret to connect using C# & ADAL and while I can get a token from Azure Active directory it lacks "something" and Business Central says it's not Authorised.

    I don't know what is missing from the token but it's smaller than the one generated via postman using client and secret and also smaller than the one generated using basic authorization.

  • EmilW Profile Picture
    25 on at

    Hi,

    I started asking the same questions in the microsoft docs for business central as i thought it's very unclear:

    github.com/.../517

    The conclusion is that it's fine to use direct tenant in production scenarios and that the basic authentication is the only option to do machine to machine scenarios. Are there any dev suggestions to implement client credentials support? I have not manage to find one, i would love to place a vote on it.

  • Community Member Profile Picture
    on at

    Thank you so much for that. I've spent days chasing a solution to this and at least now I know that there isn't one.

    Unfortunately, for external web jobs authenticating to Business Central, Basic Authentication is the worst type of authentication.

    The Dynamics team and the Azure AD team really need to sit down and solve this. Particularly with Microsoft currently trying to promote vendors to integrate their software products with Dynamics 365.

    Any external vendor who provides server side processing services will be very reluctant to use Basic Auth.

  • Suggested answer
    deldomfx Profile Picture
    15 on at

    I think with documentation in Azure portai, it's possible . Sample in C#

    MSAL initialization

    You can add the reference for MSAL by adding the following code:

    using Microsoft.Identity.Client;

    Then, initialize MSAL using the following code:

    public static IPublicClientApplication PublicClientApp;

    PublicClientApplicationBuilder.Create(ClientId)

                   .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)

                   .Build();

    Where:

    ClientId Is the Application (client) ID for the application registered in the Azure portal. You can find this value in the app's Overview page in the Azure portal.

    Requesting tokens

    MSAL has two methods for acquiring tokens: AcquireTokenInteractive and AcquireTokenSilent.

    Get a user token interactively

    Some situations require forcing users interact with the Microsoft identity platform endpoint through a popup window to either validate their credentials or to give consent. Some examples include:

    The first time users sign in to the application

    When users may need to reenter their credentials because the password has expired

    When your application is requesting access to a resource that the user needs to consent to

    When two factor authentication is required

    Copier

    authResult = await App.PublicClientApp.AcquireTokenInteractive(_scopes)

                                         .ExecuteAsync();

    Where:

    _scopes Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api:///access_as_user" } for custom Web APIs.

    Get a user token silently

    You don't want to require the user to validate their credentials every time they need to access a resource. Most of the time you want token acquisitions and renewal without any user interaction. You can use the AcquireTokenSilentAsync method to obtain tokens to access protected resources after the initial AcquireTokenInteractive method:

    var accounts = await App.PublicClientApp.GetAccountsAsync();

    var firstAccount = accounts.FirstOrDefault();

    authResult = await App.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)

                                         .ExecuteAsync();

    Where:

    scopes Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api:///access_as_user" } for custom Web APIs.

    firstAccount Specifies the first user in the cache (MSAL support multiple users in a single app).

    Next steps

  • deldomfx Profile Picture
    15 on at

    I think with documentation in Azure portai, it's possible . Sample in C#

    MSAL initialization

    You can add the reference for MSAL by adding the following code:

    using Microsoft.Identity.Client;

    Then, initialize MSAL using the following code:

    public static IPublicClientApplication PublicClientApp;

    PublicClientApplicationBuilder.Create(ClientId)

                   .WithAuthority(AzureCloudInstance.AzurePublic, Tenant)

                   .Build();

    Where:

    ClientId Is the Application (client) ID for the application registered in the Azure portal. You can find this value in the app's Overview page in the Azure portal.

    Requesting tokens

    MSAL has two methods for acquiring tokens: AcquireTokenInteractive and AcquireTokenSilent.

    Get a user token interactively

    Some situations require forcing users interact with the Microsoft identity platform endpoint through a popup window to either validate their credentials or to give consent. Some examples include:

    The first time users sign in to the application

    When users may need to reenter their credentials because the password has expired

    When your application is requesting access to a resource that the user needs to consent to

    When two factor authentication is required

    Copier

    authResult = await App.PublicClientApp.AcquireTokenInteractive(_scopes)

                                         .ExecuteAsync();

    Where:

    _scopes Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api:///access_as_user" } for custom Web APIs.

    Get a user token silently

    You don't want to require the user to validate their credentials every time they need to access a resource. Most of the time you want token acquisitions and renewal without any user interaction. You can use the AcquireTokenSilentAsync method to obtain tokens to access protected resources after the initial AcquireTokenInteractive method:

    var accounts = await App.PublicClientApp.GetAccountsAsync();

    var firstAccount = accounts.FirstOrDefault();

    authResult = await App.PublicClientApp.AcquireTokenSilent(scopes, firstAccount)

                                         .ExecuteAsync();

    Where:

    scopes Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api:///access_as_user" } for custom Web APIs.

    firstAccount Specifies the first user in the cache (MSAL support multiple users in a single app).

    Next steps

  • Nic1993 Profile Picture
    15 on at

    Did anyone have any luck with this?

    I'm also trying to get to an authorization code back from the API

    I've managed to get as far as a html response prompting to click submit to continue. Very frustrating!

  • Community Member Profile Picture
    on at

    @Nic1993

    As EmilW stated it's not actually possible to use Client/Secret to authenticate without user interaction and the reality is it wont be any time soon.

    So with basic authentication our only option we created a domain user specifically for the API connection and have put that users domain password into the app.config for our webjob. Raw domain user passwords in config files...  Arrrrrggggghhhhh

    Within our c# webjob we are using the following to grab the token (this is still prototype code but working)

    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    public async Task<v2.Common.Security.AuthenticationResult> AuthenticateBasic(string username, string password, string clientId, string tennantId) { try { string resource = "https://api.businesscentral.dynamics.com"; AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tennantId, false); UserPasswordCredential userPasswordCredential = new UserPasswordCredential(username, password);
    Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult externalResult = await authContext.AcquireTokenAsync( resource, clientId, userPasswordCredential);
    _token = new v2.Common.Security.AuthenticationResult() { Successful = true, ExternalUserId = externalResult.UserInfo.UniqueId, ExternalAuthCode = externalResult.AccessToken, // <-- this is the Bearer token ExternalAuthExpiry = externalResult.ExpiresOn.LocalDateTime, Username = externalResult.UserInfo.DisplayableId }; return _token; } catch (Exception ex) { Console.WriteLine(ex.ToString()); throw new Exception("Azure Active Directory was not able to authenticate user '" + username + "'.", ex); } }
  • Nic1993 Profile Picture
    15 on at

    David at Troovo

    Thanks David. But will this work in production environments? The API documentation states that OAuth2 Bearer tokens must be used to make calls such as Creating sales orders. etc

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Business Central

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans