How to acquire token by AD app ClientId and Client Secret with the Microsoft Authentication Library (MSAL)

2k views Asked by At

The legacy ADAL library acquires a token by Clien App ID and Client Secret, something like:

var clientID = "";
var clientSecret = "";
var aadTenantDomain = "tenant domain";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", aadTenantDomain), false);
var clientCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientID, clientSecret);
var authenticationResult = await context.AcquireTokenAsync("https://graph.microsoft.com", clientCred).ConfigureAwait(false);
return authenticationResult.AccessToken;

Given AD app ClientId and Client Secret, how can I get an access token with MSAL?

Thank you!

1

There are 1 answers

0
SiddheshDesai On BEST ANSWER

Refer below code to get the access token from client Id and Client Secret.

Code:-

using Microsoft.Identity.Client;

var clientID = "xxxxxxxx-xxxx-45b5-b838-6d26a31435cb";
var clientSecret = "xxxxxxxxxxxxxxxxxxxHiOEM6fDAQQ7BNiOLPaH.";
var aadTenantDomain = "xxxxxxxsaioutlook.onmicrosoft.com";
var authority = $"https://login.microsoftonline.com/{aadTenantDomain}";
var clientApplication = ConfidentialClientApplicationBuilder.Create(clientID)
  .WithClientSecret(clientSecret)
  .WithAuthority(authority)
  .Build();
var scopes = new string[] { "https://graph.microsoft.com/.default" };
var authenticationResult = await clientApplication.AcquireTokenForClient(scopes)
  .ExecuteAsync()
  .ConfigureAwait(false);
var accesstoken = authenticationResult.AccessToken;
Console.WriteLine(accesstoken);

Output:-

enter image description here