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):


// STS

string cloud = "";

//This is the Domain!

string tenantId = "";

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 = "";

AuthenticationContext ac = new AuthenticationContext(authority);

AuthenticationResult result = null;



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;




throw adalException;