MS Tech & Coffee

Thoughts of a .NET Developer turned into MS Dynamics architect turned into Power Platform Director turned into AI and Business Transformation Global Lead… all views are my own!

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 responses to “[Code Snippet] Dynamics 365 Web API and Azure Function v2 – Authentication using Application user”

  1. led downlights online Avatar

    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!

    1. Mario Trueba Cantero Avatar

      HI there! Thanks for reading!
      Any blogs from the https://community.dynamics.com/ would be great for you to check out!

      Also some of the ones I normally follow are:
      http://www.ramontebar.com/
      https://marcoamoedo.com/
      https://www.powernimbus.com/

      Thanks!
      Mario

Leave a comment

I’m Mario

Welcome to MS Tech & Coffee, a project I started more than 8 years ago as a place where I could drop things that I was encountering in my journey as .NET developer in the UK. That journey has taken me to many places and now looking back I want to use this project to share some of my personal views on technology, AI, the Microsoft ecosystem and of course.. a bit of coffee!

Let’s connect