-
Notifications
You must be signed in to change notification settings - Fork 379
AAD B2C specifics
This page is for MSAL 3.x onwards
If you are interested in MSAL 2.x, please see AAD B2C specifics in MSAL 2.x
You can use MSAL.NET to sign-in users with social identities by using Azure AD B2C. AAD B2C is built around the notion of policies. In MSAL.NET, specifying a policy translates to providing an authority.
- When you instantiate the Public client application, you need to specify the policy in authority
- When you want to apply a policy, you need to call an override of
AcquireTokenInteractivecontaining anauthorityparameter
The authority to use is https://login.microsoftonline.com/tfp/{tenant}/{policyName} where:
-
tenantis the name of the Azure AD B2C tenant, -
policyNamethe name of the policy to apply (for instance "b2c_1_susi" for sign-in/sign-up).
The current guidance from B2C is to use b2clogin.com as the authority. For example, $"https://{your-tenant-name}.b2clogin.com/tfp/{your-tenant-ID}/{policyname}". For more information, see this documentation.
// Azure AD B2C Coordinates
public static string Tenant = "fabrikamb2c.onmicrosoft.com";
public static string ClientID = "90c0fe63-bcf2-44d5-8fb7-b8bbc0b29dc6";
public static string PolicySignUpSignIn = "b2c_1_susi";
public static string PolicyEditProfile = "b2c_1_edit_profile";
public static string PolicyResetPassword = "b2c_1_reset";
public static string AuthorityBase = $"https://fabrikamb2c.b2clogin.com/tfp/{Tenant}/";
public static string Authority = $"{AuthorityBase}{PolicySignUpSignIn}";
public static string AuthorityEditProfile = $"{AuthorityBase}{PolicyEditProfile}";
public static string AuthorityPasswordReset = $"{AuthorityBase}{PolicyResetPassword}";When building the application, you need to provide, as usual, the authority, built as above
application = PublicClientApplicationBuilder.Create(ClientID)
.WithB2CAuthority(Authority)
.Build();Starting with MSAL .NET 4.15.0, developers will no longer have to write their own cache filtering logic.
In Azure AD B2C, each policy, or user flow, is a separate authorization server. They issue their own tokens. So a token acquired using the b2c_1_editprofile user flow will not work with a resource protected behind a b2c_1_susi user flow. Therefore, when calling a protected API, application developers must let MSAL know which token to use from the cache, based on the user flow that will be targeted.
Acquiring a token for an Azure AD B2C protected API in a public client application requires you to use:
- the override of GetAccountsAsync() with a user flow before calling AcquireTokenSilent,
- the overrides AcquireTokenXXX with a B2C authority:
IEnumerable<IAccount> accounts = await application.GetAccountsAsync(B2CConstants.PolicySignUpSignIn);
AuthenticationResult ar = await application.AcquireTokenInteractive(B2CConstants.Scopes)
.WithAccount(accounts.FirstOrDefault())
.ExecuteAsync();In versions > 4.15.0, developers had to write their own cache filtering logic. This is no longer the case in >= 4.15.0, as developers only need to specify the policy, or user flow, and MSAL will return the corresponding account for that specific user flow.
| In MSAL < 4.15.0, developers would need to write: | In MSAL >= 4.15.0, developers now only write: |
private IAccount GetAccountByPolicy(IEnumerable<IAccount> accounts, string policy)
{
foreach (var account in accounts)
{
string userIdentifier = account.HomeAccountId.ObjectId.Split('.')[0];
if (userIdentifier.EndsWith(policy.ToLower()))
return account;
}
return null;
} |
var accounts = await app.GetAccountsAsync(App.PolicySignUpSignIn); |
Applying a policy (for instance letting the end user edit their profile or reset their password) is currently done by calling AcquireTokenInteractive.
Note that in the case of these two policies you don't use the returned token / authentication result.
When you want to provide an experience where your end users sign-in with a social identity, and then edit their profile you want to apply the B2C EditProfile policy. The way to do this, is by calling AcquireTokenInteractive with
the specific authority for that policy and a Prompt set to Prompt.NoPrompt to avoid the account selection dialog to be displayed (as the user is already signed-in)
private async void EditProfileButton_Click(object sender, RoutedEventArgs e)
{
IEnumerable<IAccount> accounts = await app.GetAccountsAsync();
try
{
var authResult = await app.AcquireToken(scopes:App.ApiScopes)
.WithAccount(GetUserByPolicy(accounts, App.PolicyEditProfile)),
.WithPrompt(Prompt.NoPrompt),
.WithB2CAuthority(App.AuthorityEditProfile)
.ExecuteAsync();
DisplayBasicTokenInfo(authResult);
}
catch
{
. . .
}For more details on the ROPC flow, please see this documentation.
This flow is not recommended because your application asking a user for their password is not secure. For more information about this problem, see this article.
By using username/password you are giving-up a number of things:
- core tenants of modern identity: password gets fished, replayed. Because we have this concept of a share secret that can be intercepted. This is incompatible with passwordless.
- users who need to do MFA won't be able to sign-in (as there is no interaction)
- Users won't be able to do single sign-on
In your AzureAD B2C tenant, create a new user flow and select Sign in using ROPC. This will enable the ROPC policy for your tenant. See Configure the resource owner password credentials flow for more details.
IPublicClientApplication contains a method called
AcquireTokenByUsernamePassword(
IEnumerable<string> scopes,
string username,
SecureString password)This method takes as parameters:
- The
scopesto request an access token for - A username
- A SecureString password for the user
Remember to use the authority which contains the ROPC policy.
- This only works for local accounts (where you register with B2C using an email or username). This flow does not work if federating to any of the IdPs supported by B2C (Facebook, Google, etc...).
If you are a B2C developer using Google as an identity provider we recommand you use the system browser, as Google does not allow authentication from embedded webviews. Currently, login.microsoftonline.com is a trusted authority with Google. Using this authority will work with embedded webview. However using b2clogin.com is not a trusted authority with Google, so users will not be able to authenticate.
We will provide an update to the wiki and this issue if things change.
MSAL.Net supports a [token cache] (https://docs.microsoft.com/en-us/dotnet/api/microsoft.identity.client.tokencache?view=azure-dotnet). The token caching key is based on the claims returned by the Identity Provider. Currently MSAL.Net needs two claims to build a token cache key: :
-
tidwhich is the Azure AD Tenant Id and preferred_username
Both these claims are missing in many of the Azure AD B2C scenarios.
The customer impact is that when trying to display the username field, are you getting "Missing from the token response" as the value? If so, this is because B2C does not return a value in the IdToken for the preferred_username because of limitations with the social accounts and external identity providers (IdPs). Azure AD returns a value for preferred_username because it knows who the user is, but for B2C, because the user can sign in with a local account, Facebook, Google, GitHub, etc...there is not a consistent value for B2C to use for preferred_username. To unblock MSAL from rolling out cache compatibility with ADAL, we decided to use "Missing from the token response" on our end when dealing with the B2C accounts when the IdToken returns nothing for preferred_username. MSAL must return a value for preferred_username to maintain cache compatibility across libraries.
The suggested workaround is to use the [Caching by Policy] (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/AAD-B2C-specifics#acquiring-a-token-to-apply-a-policy)
Alternatively, you can use the tid claim, if you are using the [B2C custom policies] (https://aka.ms/ief), because it provides the capability to return additional claims to the application. To learn more about Claims Transformation
One option is to use the "name" claim as the preferred username. The process is generally mentioned in this B2C doc ->
"In the Return claim column, choose the claims you want returned in the authorization tokens sent back to your application after a successful profile editing experience. For example, select Display Name, Postal Code.”
| Sample | Platform | Description |
|---|---|---|
| active-directory-b2c-xamarin-native | Xamarin iOS, Xamarin Android, UWP | A simple Xamarin Forms app showcasing how to use MSAL.NET to authenticate users via Azure Active Directory B2C, and access a Web API with the resulting tokens. |
- 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
- 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
- AcquireTokenInteractive
- WAM - the Windows broker
- .NET Core
- Maui Docs
- 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
- High Availability
- Regional
- 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