[Code Snippet] Dynamics 365 Web API and Azure Function v2 – Authentication using Application user

This is just the code part of the authentication, for a full explanation of how I got here please refer to the main article.

Main Article

Disclaimer: This is by no means a best practice post so please if you have a better way of doing it feel free to share in the comments, I will be really happy to update the main code. This is just how I am doing it right now.

Nuget Packages that I have used. (versions might of course change in time):

dependency1dependency2


// STS

string cloud = "https://login.microsoftonline.com";

//This is the Domain!

string tenantId = "DOMAIN.onmicrosoft.com";

string authority = $"{cloud}/{tenantId}";

// ApplicationID in the new UI

string clientId = "APPLICATION ID IN THE APP";

//Created from scratch in Keys

string clientsecret = "YOU NEED TO REQUEST THAT IN KEYS";

ClientCredential clientcred = new ClientCredential(clientId, clientsecret);

// Application ID of the Resource (could also be the Resource URI)

string resource = "https://YOURENVIRONEMNT.crm4.dynamics.com";

AuthenticationContext ac = new AuthenticationContext(authority);

AuthenticationResult result = null;

try

{

result = await ac.AcquireTokenSilentAsync(resource, clientId);

return result.AccessToken;

}

catch (AdalException adalException)

{

if (adalException.ErrorCode == AdalError.FailedToAcquireTokenSilently

|| adalException.ErrorCode == AdalError.InteractionRequired)

{

result = await ac.AcquireTokenAsync(resource, clientcred);

return result.AccessToken;

}

else

{

throw adalException;

}

}

3 thoughts on “[Code Snippet] Dynamics 365 Web API and Azure Function v2 – Authentication using Application user

  1. Pingback: Dynamics 365 Web API and Azure Function v2 – Authentication using Application user | CRM & Coffee

  2. Hi there! This is my 1stcomment here so I just wanted to give a quick shout ouut and say I genuinely enjoyy reafing your
    blog posts. Can you recommend any other blogs/websites/forums that go over the same subjects?
    Apprciate it!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s