Skip to content

Acquiring tokens interactively

Jean-Marc Prieur edited this page Apr 12, 2019 · 43 revisions

This article is about MSAL.NET 3.x. If you are interested in MSAL.NET 2.x go to Acquiring tokens interactively in MSAL 2.x

AcquireTokenInteractive

The following example shows minimal code to get a token for reading the user's profile with Microsoft Graph.

string[] scopes = new string["user.read"];
var app = PublicClientApplicationBuilder.Create(clientId).Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result;
try
{
 result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
             .ExecuteAsync();
}
catch(MsalUiRequiredException)
{
 result = await app.AcquireTokenInteractive(scopes)
             .ExecuteAsync();
}

Mandatory parameters

The parameters are the following:

  • Scopes contains an enumeration of strings which define the scopes for which a token is required. If the token is for the Microsoft Graph, the required scopes can be found in api reference of each Microsoft graph API in the section named "Permissions". For instance, to list the user's contacts, the scope "User.Read", "Contacts.Read" will need to be used. See also Microsoft Graph permissions reference.

Optional parameters

UI Parent

  • parent is an object, which can be null. It enables, for platforms supporting it, to specify the parent UI (window in Windows, Activity in Android, .) which will be the parent of the interactive dialog. See below
  • Note that on Windows, you must call AcquireTokenInteractive on the UI thread so that the embedded browser gets the appropriate UI synchronization context. Not calling from the UI thread may cause messages to not pump properly and/or deadlock scenarios with the UI.
Builder modifier Description
WithAuthority (7 overrides) Overrides the authority
WithAdfsAuthority(string) Overrides the authority
WithB2CAuthority(string) Overrides the authority
WithAccount(IAccount) account (optional) of type IAccount, provides a hint to the STS about the user for which to get the token. This can be set from the Account member of a previous AuthenticationResult, or one of the elements of the collection returned by GetAccountsAsync() method of the PublicClientApplication.
WithLoginHint(string) loginHint (optional) offers a hint to the STS about the user for which to get the token alternative to user. It's used like userIdentifier in ADAL. Needs to be passed the preferred_username of the IDToken (contrary to ADAL which was requiring the UPN)
WithClaims(string) Requests additional claims. This normally is in reaction to an MsalClaimChallengeException which has a Claim member (Conditional Access)
WithPrompt(Prompt) Is the way to control, in MSAL.NET, the interaction between the user and the STS to enter credentials. It's different depending on the platform (See below). Note that MSAL 3.x is taking a breaking change here. Prompt used to be named UIBehavior in MSAL 1.x and 2.x
WithExtraQueryParameters(dictionary) A dictionary of keys / values.
WithExtraScopesToConsent(extraScopes) Enables application developers to specify additional scopes for which users will pre-consent. This can be in order to avoid having them see incremental consent screens when the Web API require them. This is also indispensable in the case where you want to provide scopes for several resources. See the paragraph on getting consent for several resources below for more details.

How to?

Control the interactivity with the user by specifying a Prompt

The public members are:

  • Consent: enables the application developer to force the user be prompted for consent even if consent was granted before. This is done by sending prompt=consent to the identity provider.
  • ForceLogin: enables the application developer to have the user prompted for credentials by the service even if this would not be needed. This can be useful if Acquiring a token fails, to let the user re-sign-in. This is done by sending prompt=login to the identity provider.
  • Never (for .NET 4.5 and WinRT only) will not prompt the user, but instead will try to use the cookie stored in the hidden embedded web view (See below: Web Views in MSAL.NET). This might fail, and in that case AcquireTokenInteractive will throw an exception to notify that a UI interaction is needed, and you'll need to use another Prompt parameter.
  • SelectAccount: will force the STS to present the account selection dialog containing accounts for which the user has a session. This is useful when applications developers want to let user choose among different identities. This is done by sending prompt=select_account to the identity provider.
  • NoPrompt: Won't send any prompt to the identity provider. This is actually only useful in the case of B2C edit profile policies (See B2C specifics).

Control the location of the dialog with the parent parameter (object)

UIParent is used, on the platforms allowing it, to specify the parent window for the authentication dialog.

  • For .NET 4.5 and WinRT, it provides a constructor with an object: the OwnerWindow parameter.
  • For Android, it provides a constructor with the parent Activity. Here's an example for Android.
  • For iOS, use the default constructor of UIParent. Create the UIParent in the AppDelegate class. Here's an example for iOS.

Have the user consent upfront for several resources

Note: Getting consent for several resources works for Azure AD v2.0, but not for Azure AD B2C. B2C supports only admin consent, not user consent.

The Azure AD v2.0 endpoint does not allow you to get a token for several resources at once. Therefore the scopes parameter should only contain scopes for a single resource. However, you can ensure that the user pre-consents to several resources by using the extraScopesToConsent parameter.

For instance if you have two resources, which have 2 scopes each:

  • https://mytenant.onmicrosoft.com/customerapi (with 2 scopes customer.read and customer.write)
  • https://mytenant.onmicrosoft.com/vendorapi (with 2 scopes vendor.read and vendor.write)

you should use the .WithAdditionalPromptToConsent modifier which has the extraScopesToConsent parameter

For instance:

string[] scopesForCustomerApi = new string[]
{
  "https://mytenant.onmicrosoft.com/customerapi/customer.read",
  "https://mytenant.onmicrosoft.com/customerapi/customer.write"
};
string[] scopesForVendorApi = new string[] 
{
 "https://mytenant.onmicrosoft.com/vendorapi/vendor.read", 
 "https://mytenant.onmicrosoft.com/vendorapi/vendor.write" 
};

var accounts = await app.GetAccountsAsync();
var result = await app.AcquireTokenInteractive(scopesForCustomerApi)
                     .WithAccount(accounts.FirstOrDefault())
                     .WithExtraScopeToConsent(scopesForVendorApi)
                     .ExecuteAsync();

This will get you an access token for the first Web API. Then when you need to call the second one, you can call

AcquireTokenSilent(scopesForVendorApi, accounts.FirstOrDefault()).ExecuteAsync();

See this GitHub issue for more context.

Microsoft personal account require re-consenting each time the app is run

For Microsoft personal accounts users, re-prompting for consent on each native client call to authorize is the intended behavior. Native client identity is inherently insecure, and the Microsoft identity platform chose to mitigate this insecurity for consumer services by prompting for consent each time the application is authorized.

More specificities depending on the platforms

Depending on the platforms, you will need to do a bit of extra work to use MSAL.NET. For more details on each platform, see:

Samples illustrating acquiring tokens interactively with MSAL.NET

Sample Platform Description
active-directory-dotnet-desktop-msgraph-v2 Desktop (WPF) Windows Desktop .NET (WPF) application calling the Microsoft Graph API.
active-directory-dotnet-native-uwp-v2 UWP A Windows Universal Platform client application using msal.net, accessing the Microsoft Graph for a user authenticating with Azure AD v2.0 endpoint.
https://github.com/Azure-Samples/active-directory-xamarin-native-v2 Xamarin iOS, Android, UWP A simple Xamarin Forms app showcasing how to use MSAL to authenticate MSA and Azure AD via the AADD v2.0 endpoint, and access the Microsoft Graph with the resulting token.
https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore-v2 WPF, ASP.NET Core 2.0 Web API A WPF application calling an ASP.NET Core Web API using Azure AD v2.0.

Getting started with MSAL.NET

Acquiring tokens

Desktop/Mobile apps

Web Apps / Web APIs / daemon apps

Advanced topics

News

FAQ

Other resources

Clone this wiki locally