Skip to content

Latest commit

 

History

History
251 lines (175 loc) · 12.3 KB

File metadata and controls

251 lines (175 loc) · 12.3 KB
page_type languages products name urlFragment description
sample
csharp
aspnet-core
azure-active-directory-b2c
Enable your Blazor Server to sign-in users with the Microsoft identity platform in Azure AD B2C
ms-identity-blazor-server
This sample demonstrates how to enable your Blazor Server to sign-in users against Azure AD B2C

Enable your Blazor Server to sign-in users with the Microsoft identity platform in Azure AD B2C

  1. Overview
  2. Scenario
  3. Prerequisites
  4. Setup
  5. Registration
  6. Running the sample
  7. Explore the sample
  8. About the code
  9. Next chapter of the tutorial: the Web app calls Web API
  10. More information
  11. Community Help and Support
  12. Contributing

.NET Core

Overview

This sample demonstrates an ASP.NET Core Blazor Server standalone application that authenticates users against Azure AD B2C.

This application uses Implicit flow grant type provided by Microsoft identity platform.

Overview

Scenario

  1. The ASP.NET Core Blazor Server standalone app uses the Microsoft Authentication Library to obtain an ID Token from Azure AD B2C:
  2. The ID Token proves that the user has successfully authenticated against Azure AD B2C.

Prerequisites

Setup

In the downloaded folder

From your shell or command line:

cd ms-identity-blazor-server\WebApp-OIDC\B2C

⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.

Registration

⚠️ This sample comes with a pre-registered application for testing purposes. If you would like to use your own Azure AD B2C tenant and application, follow the steps below to register and configure the application in the Azure portal. Otherwise, continue with the steps for Running the sample.

Register the sample application(s) with your Azure Active Directory tenant

There is one project in this sample. To register it, you can follow the steps below to manually register your apps.

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal.
  2. 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.

Create User Flows and Custom Policies

Please refer to: Tutorial: Create user flows in Azure Active Directory B2C

Add External Identity Providers

Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C

Register the web app (WebApp-blazor-server-b2c)

  1. Navigate to the Azure portal and select the Azure AD B2C service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. 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-blazor-server-b2c.
    • Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows).
    • In the Redirect URI 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.

  4. Confirm that Permissions > Grant admin consent to openid and offline_access permissions is selected.
  5. Select Register to create the application.
  6. 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.
  7. In the app's registration screen, select Authentication in the menu.
    • In the Redirect URIs section, enter the following redirect URIs.
      • https://localhost:44365/signin-oidc
    • In the 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.
  8. Select Save to save your changes.

Configure the web app (WebApp-blazor-server-b2c) to use your app registration

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".

  1. Open the blazorserver-B2C\appsettings.json file.
  2. Find the key Instance and replace the value with your tenant name. For example, https://fabrikam.b2clogin.com
  3. Find the key ClientId and replace the existing value with the application ID (clientId) of the WebApp-blazor-server-b2c application copied from the Azure portal.
  4. Find the key Domain and replace the existing value with your Azure AD tenant name.
  5. Find the key SignUpSignInPolicyId and replace with the name of the Sign up and sign in policy you created.
  6. Find the key ResetPasswordPolicyId and replace with the name of the Password reset policy you created.
  7. Find the key EditProfilePolicyId and replace with the name of the Profile editing policy you created.

Running the sample

You can run the sample by using either Visual Studio or command line interface as shown below:

Run the sample using Visual Studio

Clean the solution, rebuild the solution, and run it.

Run the sample using a command line interface such as VS Code integrated terminal

Step 1. Install .NET Core dependencies

cd WebApp-OIDC\B2C
cd blazorserver-B2C
dotnet restore

Step 2. Trust development certificates

dotnet dev-certs https --clean
dotnet dev-certs https --trust

Learn more about HTTPS in .NET Core.

Step 3. Run the applications

In the console window execute the below command:

dotnet run

Explore the sample

If you are using incognito mode of browser to run this sample then allow third party cookies.

  1. Open your browser and navigate to https://localhost:44365.
  2. Select the Sign in button on the top right corner. You will see claims from the signed-in user's token.

UserClaims

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback!

Were we successful in addressing your learning objective? Do consider taking a moment to share your experience with us.

How was the code created

Create the Web App using Blazor Server template:

  1. Create the Web App using Blazor Server template:

    dotnet new blazorserver --auth IndividualB2C
  2. Add UserClaims.razor component and UserClaimsBase.cs class.

About the code

  1. In Startup.cs, add below lines of code in ConfigureServices method:

    services.AddMicrosoftIdentityWebAppAuthentication(Configuration, "AzureAdB2C");

    This enables your application to authenticate users.

  2. 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 identity provider.

  3. 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.";
           }
       }
    }

Next chapter of the tutorial: the Web app calls Web API

Navigate to the chapter Secure and call a Web API with the Microsoft identity platform to learn about securing and calling Web APIs.

More information

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

Community Help and Support

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.

Contributing

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 [email protected] with any additional questions or comments.