-
Notifications
You must be signed in to change notification settings - Fork 343
Acquiring tokens interactively
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
- In MSAL.NET 3.x, the method to use to acquire a token interactively is
AcquireTokenInteractive
- See Acquiring tokens interactively in MSAL 2.x for information about overrides of
AcquireTokenAsync
.
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();
AuthenticationResult result;
try
{
result = await app.AcquireTokenSilent(scopes)
.ExecuteAsync();
}
catch(MsalUiRequiredException)
{
result = await app.AcquireTokenInteractive(scopes, null)
.ExecuteAsync();
}
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. -
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
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. |
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 sendingprompt=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 sendingprompt=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 caseAcquireTokenInteractive
will throw an exception to notify that a UI interaction is needed, and you'll need to use anotherPrompt
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 sendingprompt=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).
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 theUIParent
in theAppDelegate
class. Here's an example for iOS.
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 scopescustomer.read
andcustomer.write
) -
https://mytenant.onmicrosoft.com/vendorapi
(with 2 scopesvendor.read
andvendor.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.
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.
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:
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. |
- Home
- Why use MSAL.NET
- Is MSAL.NET right for me
- Scenarios
- Register your app with AAD
- Client applications
- Acquiring tokens
- MSAL samples
- Known Issues
- AcquireTokenInteractive
- WAM - the Windows broker
- .NET Core
- Xamarin Docs
- UWP
- Custom Browser
- Applying an AAD B2C policy
- Integrated Windows Authentication for domain or AAD joined machines
- Username / Password
- Device Code Flow for devices without a Web browser
- ADFS support
- Acquiring a token for the app
- Acquiring a token on behalf of a user in Web APIs
- Acquiring a token by authorization code in Web Apps
- High Availability
- Token cache serialization
- Logging
- Exceptions in MSAL
- Provide your own Httpclient and proxy
- Extensibility Points
- Clearing the cache
- Client Credentials Multi-Tenant guidance
- Performance perspectives
- Differences between ADAL.NET and MSAL.NET Apps
- PowerShell support
- Testing apps that use MSAL
- Experimental Features
- Proof of Possession (PoP) tokens
- Using in Azure functions
- Extract info from WWW-Authenticate headers
- SPA Authorization Code