Paul Dolphin
Paul Dolphin

Reputation: 798

How do you use AcquireTokenSilentAsync to authenticate a user?

I am attempting to programmatically authorise an Azure application from an Azure AD joined machine.

If I go to the application URL in Internet Explorer it is able to verify the logged on user account.

My current code looks something like this:

using Microsoft.IdentityModel.Clients.ActiveDirectory;

AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/TENANTGUID");
Uri uri = new Uri("urn:ietf:wg:oauth:2.0:oob");
var pparams = new PlatformParameters(PromptBehavior.Auto, null);
AuthenticationResult result = await context.AcquireTokenAsync("https://graph.windows.net", "1950a258-227b-4e31-a9cf-717495945fc2", uri, pparams);

This call is successful but I want to acquire a token for the currently logged on user.

The first two parameters to the AcquireTokenAsync call are resource and clientid.

I can get the Homepage url and application id for the application I want to access but cannot find a combination of the two that works.

What parameters should I pass to this function to silently validate the logged on user and obtain an authorisation header that can be used in subsequent calls to the application?

Upvotes: 0

Views: 7023

Answers (1)

Jean-Marc Prieur
Jean-Marc Prieur

Reputation: 1651

I'd advise you now MSAL.NET Integrated Windows Authentication for domain or AAD joined machines:

the code would be something like :

static async Task GetATokenForGraph()
{
 string tenant = "contoso.com" // can also be a GUID or organizations for multi-tenant
 string authority = $"https://login.microsoftonline.com/{tenant}";
 string[] scopes = new string[] { "user.read" };
 PublicClientApplication app = new PublicClientApplication(clientId, authority);
 var accounts = await app.GetAccountsAsync();

 AuthenticationResult result=null;
 if (accounts.Any())
 {
 result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault());
 }
 else
 {
  try
  {
   result = await app.AcquireTokenByIntegratedWindowsAuthAsync(scopes);
  }
  catch (MsalUiRequiredException ex)
   { 
    // For details see the article 

Upvotes: 1

Related Questions