in DeviceProfileSample/Program.cs [60:96]
private static async Task<AuthenticationResult> SignInUserAndGetTokenUsingMSAL(string[] scopes)
{
// Initialize the MSAL library by building a public client application
application = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithDefaultRedirectUri()
.Build();
AuthenticationResult result;
try
{
var accounts = await application.GetAccountsAsync();
// Try to acquire an access token from the cache. If device code is required, Exception will be thrown.
result = await application.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
result = await application.AcquireTokenWithDeviceCode(scopes, deviceCodeResult =>
{
// This will print the message on the console which tells the user where to go sign-in using
// a separate browser and the code to enter once they sign in.
// The AcquireTokenWithDeviceCode() method will poll the server after firing this
// device code callback to look for the successful login of the user via that browser.
// This background polling (whose interval and timeout data is also provided as fields in the
// deviceCodeCallback class) will occur until:
// * The user has successfully logged in via browser and entered the proper code
// * The timeout specified by the server for the lifetime of this code (typically ~15 minutes) has been reached
// * The developing application calls the Cancel() method on a CancellationToken sent into the method.
// If this occurs, an OperationCanceledException will be thrown (see catch below for more details).
Console.WriteLine(deviceCodeResult.Message);
return Task.FromResult(0);
}).ExecuteAsync();
}
return result;
}