page_type | languages | products | name | urlFragment | description | |||||
---|---|---|---|---|---|---|---|---|---|---|
sample |
|
|
Enable your Blazor Server to sign-in users and call web API with the Microsoft identity platform in Azure AD B2C |
ms-identity-blazor-server |
This sample demonstrates an ASP.NET Core Blazor Server application calling an ASP.NET Core web API that is secured using Azure AD B2C |
Enable your Blazor Server to sign-in users and call web API with the Microsoft identity platform in Azure AD B2C
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
- Code of Conduct
This sample demonstrates an ASP.NET Core Blazor Server application calling an ASP.NET Core web API that is secured using Azure AD B2C.
- The client ASP.NET Core Blazor Server application uses the Microsoft Authentication Library MSAL.Net and Microsoft.Identity.Web libraries to sign-in and obtain a JWT Access Token from Azure AD B2C.
- The Access Token is used as a bearer token to authorize the user to call secure ASP.NET Core web API.
- Visual Studio
- An Azure AD B2C tenant. For more information see: How to get an Azure AD B2C tenant
- A user account in your Azure AD B2C tenant.
From your shell or command line:
cd ms-identity-blazor-server\WebApp-your-API\B2C
As a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD B2C tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD B2C tenant.
Please refer to: Tutorial: Create user flows in Azure Active Directory B2C
Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C
- Navigate to the Azure portal and select the Azure AD B2C service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
ToDoListService-aspnetcore
. - Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an Api for which client applications can obtain access tokens for.
The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this Api. To declare an resource URI, follow the following steps:
- Select
Set
next to the Application ID URI to generate a URI that is unique for this app. - For this sample, accept the proposed Application ID URI (
https://{tenantName}.onmicrosoft.com/{clientId}
) by selecting Save.
- Select
- All Apis have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user
. - For Admin consent display name type
Access TodoListService-aspnetcore-webapi
. - For Admin consent description type
Allows the app to access TodoListService-aspnetcore-webapi as the signed-in user.
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
Service\appsettings.json
file. - Find the key
Instance
and replace the value with your tenant name. For example,https://fabrikam.b2clogin.com
- Find the key
ClientId
and replace the existing value with the application ID (clientId) of theToDoListService-aspnetcore
application copied from the Azure portal. - Find the key
Domain
and replace the existing value with your Azure AD tenant name. - Find the key
SignedOutCallbackPath
and add the name of theSign up and sign in
policy you created. - Find the key
SignUpSignInPolicyId
and replace with the name of theSign up and sign in
policy you created.
- Navigate to the Azure portal and select the Azure AD B2C service.
- Select the App Registrations blade on the left, then select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
WebApp-calls-API-blazor-server
. - Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
- In the Redirect URI (optional) section, select Web in the combo-box and enter the following redirect URI:
https://localhost:44365/
.Note that there are more than one redirect URIs used in this sample. You'll need to add them from the Authentication tab later after the app has been created successfully.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select Authentication in the menu.
- If you don't have a platform added, select Add a platform and select the Web option.
- In the Redirect URIs section, enter the following redirect URIs.
https://localhost:44365/signin-oidc
- In the Front-channel logout URL section, set it to
https://localhost:44365/signout-oidc
. - In Implicit grant section, select the check boxes for Access tokens and ID tokens.
- Select Save to save your changes.
- In the app's registration screen, select the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
- In the Client secrets section, select New client secret:
- Type a key description (for instance
app secret
), - Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security posture.
- The generated key value will be displayed when you select the Add button. Copy the generated value for use in the steps later.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Select the Add a permission button and then,
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
ToDoListService-aspnetcore
. - In the Delegated permissions section, select the Access 'ToDoListService-aspnetcore' in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Select Grant admin consent.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
Client\appsettings.json
file. - Find the key
Instance
and replace the value with your tenant name. For example,https://fabrikam.b2clogin.com
- Find the key
ClientId
and replace the existing value with the application ID (clientId) of theWebApp-calls-API-blazor-server
application copied from the Azure portal. - Find the key
Domain
and replace the existing value with your Azure AD tenant name. - Find the key
SignedOutCallbackPath
and add the name of theSign up and sign in
policy you created. - Find the key
SignUpSignInPolicyId
and replace with the name of theSign up and sign in
policy you created. - Find the key
ResetPasswordPolicyId
and replace with the name of thePassword reset
policy you created. - Find the key
EditProfilePolicyId
and replace with the name of theProfile editing
policy you created. - Find the key
ClientSecret
and replace the existing value with the key you saved during the creation of theWebApp-calls-API-blazor-server
app, in the Azure portal. - Find the key
TodoListScope
and replace the value with API Scope defined in the Azure portal. - Find the key
TodoListBaseAddress
and replace the existing value with the base address of the ToDoListService-aspnetcore project (by defaulthttps://localhost:44332
).
You can run the sample by using either Visual Studio or command line interface as shown below:
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with the service project starting first.
When you start the web API from Visual Studio, depending on the browser you use, you'll get:
- an empty web page (with Microsoft Edge)
- or an error HTTP 401 (with Chrome)
This behavior is expected as the browser is not authenticated. The Web application will be authenticated, so it will be able to access the web API.
cd Client
dotnet restore
Then:
In a separate console window, execute the following commands
cd Service
dotnet restore
dotnet dev-certs https --clean
dotnet dev-certs https --trust
Learn more about HTTPS in .NET Core.
In both the console windows execute the below command:
dotnet run
If you are using incognito mode of browser to run this sample then allow third party cookies.
-
Open your browser and navigate to
https://localhost:44365
. -
Select the Sign in button on the top right corner. You will see claims from the signed-in user's token.
-
Select ToDoList from navigation bar and you can create, edit or delete the todo list items.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Do consider taking a moment to share your experience with us.
-
In
Startup.cs
, add below lines of code in ConfigureServices method:services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C") .EnableTokenAcquisitionToCallDownstreamApi(new string[] { Configuration["TodoList:TodoListScope"] }) .AddInMemoryTokenCaches();
This enables your application to use the Microsoft identity platform endpoint to sign-in users and to call the protected web API.
The following code registers client service to use the HttpClient by dependency injection.
services.AddToDoListService(Configuration);
Below code adds the incremental consent and conditional access handler for Blazor server side pages.
services.AddServerSideBlazor() .AddMicrosoftIdentityConsentHandler();
-
Index.razor is the landing page when application starts. Index.razor contains child component called
UserClaims
. If user is authenticated successfully,UserClaims
displays a few claims present in the ID Token issued by Azure AD. -
In the
UserClaimsBase.cs
class, GetClaimsPrincipalData method retrieves signed-in user's claims using the GetAuthenticationStateAsync() method of the AuthenticationStateProvider class.public class UserClaimsBase : ComponentBase { [Inject] private AuthenticationStateProvider AuthenticationStateProvider { get; set; } protected string _authMessage; protected IEnumerable<Claim> _claims = Enumerable.Empty<Claim>(); private string[] printClaims = { "name", "idp", "oid", "jobTitle", "emails" }; protected override async Task OnInitializedAsync() { await GetClaimsPrincipalData(); } private async Task GetClaimsPrincipalData() { var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync(); var user = authState.User; if (user.Identity.IsAuthenticated) { _authMessage = $"{user.Identity.Name} is authenticated."; _claims = user.Claims.Where(x => printClaims.Contains(x.Type)); } else { _authMessage = "The user is NOT authenticated."; } } }
-
ToDoList.razor component displays list of items created by signed-in user. List can be updated and deleted.
ToDoListBase.cs
calls GetToDoListService method to retrieve the todo list.public class ToDoListBase : ComponentBase { [Inject] ToDoListService ToDoListService { get; set; } [Inject] MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler { get; set; } [Inject] NavigationManager Navigation { get; set; } protected IEnumerable<ToDo> toDoList = new List<ToDo>(); protected ToDo toDo = new ToDo(); protected override async Task OnInitializedAsync() { await GetToDoListService(); } [AuthorizeForScopes(ScopeKeySection = "TodoList:TodoListScope")] private async Task GetToDoListService() { try { toDoList = await ToDoListService.GetAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); ConsentHandler.HandleException(ex); } } protected async Task DeleteItem(int Id) { await ToDoListService.DeleteAsync(Id); await GetToDoListService(); } }
-
ToDoListService.cs
class in client project defines method to call protected API. PrepareAuthenticatedClient method retrieves the Access Token for the web API and sets authorization and accept headers for the request.private async Task PrepareAuthenticatedClient() { var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { _TodoListScope }); Debug.WriteLine($"access token-{accessToken}"); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }
- What is Azure Active Directory B2C?
- Application types that can be used in Active Directory B2C
- Recommendations and best practices for Azure Active Directory B2C
- Azure AD B2C session
- Secure ASP.NET Core Blazor Server apps
- ASP.NET Core Blazor Server additional security scenarios
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory
azure-ad-b2c
ms-identity
msal
].
If you find a bug in the sample, raise the issue on GitHub Issues.
To provide feedback on or suggest features for Azure Active Directory, visit User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.