Skip to content
This repository was archived by the owner on May 17, 2024. It is now read-only.

Latest commit

 

History

History
337 lines (247 loc) · 20.7 KB

File metadata and controls

337 lines (247 loc) · 20.7 KB
page_type sample
description This sample demonstrates an Angular single-page application (SPA) calling a ASP.NET Core web API secured with Azure AD B2C. It uses the Microsoft Authentication Library for Angular (MSAL Angular) to sign-in a users in the SPA and get a token for the web API. The Web API is protected using the Microsoft.Identity.Web.
languages
javascript
typescript
csharp
products
azure-active-directory-b2c
msal-js
msal-angular
microsoft-identity-web
microsoft-authentication-library
entra
urlFragment spa-msal-angular-b2c-netcore
extensions
services platform endpoint level client service
ms-identity
JavaScript
AAD v2.0
200
Angular SPA
.NET Core web API

Angular single-page application that authenticates users with Azure AD B2C and calls a protected .NET Core web API

Overview

This sample demonstrates an Angular single-page application (SPA) calling a ASP.NET Core web API secured with Azure AD B2C. It uses the Microsoft Authentication Library for Angular (MSAL Angular) to sign-in a users in the SPA and get a token for the web API. The Web API is protected using the Microsoft.Identity.Web.

ℹ️ To learn how to integrate a JavaScript Angular application with Azure AD,consider going through the recorded session: Deep dive on using MSAL.js to integrate Angular single-page applications with Azure Active Directory

Scenario

  1. The client Angular SPA uses MSAL Angular to sign-in a user and obtain a JWT Access Token from Azure AD B2C.
  2. The access token is used as a bearer token to authorize the user to call the .NET Core web API protected by Azure AD B2C.
  3. The service uses the Microsoft.Identity.Web to protect the Web api, check permissions and validate tokens.

Scenario Image

Contents

File/folder Description
SPA/src/app/auth-config.ts Authentication parameters for SPA project reside here.
SPA/src/app/app.module.ts MSAL Angular is initialized here.
API/TodoListAPI/appsettings.json Authentication parameters for API project reside here.
API/TodoListAPI/Startup.cs Microsoft.Identity.Web is initialized here.
API/TodoListAPI/Controllers/TodoListController.cs Contains logic for controlling access to data.

Prerequisites

Setup the sample

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.git

or download and extract the repository .zip file.

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

Step 2. Install .NET Core API dependencies

    cd ms-identity-javascript-angular-tutorial
    cd 3-Authorization-II/2-call-api-b2c/API/TodoListAPI
    dotnet restore

Step 3. Trust development certificates

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

For more information and potential issues, see: HTTPS in .NET Core.

Step 4. Install Angular SPA dependencies

    cd ../
    cd SPA
    npm install

Step 5: Register the sample application(s) in your tenant

⚠️ This sample comes with a pre-registered application for demo 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 on Azure portal. Otherwise, continue with the steps for Explore the sample.

Choose the Azure AD B2C 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 service app (msal-dotnet-api)

  1. Navigate to the Azure portal and select the Azure Active Directory 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:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-dotnet-api.
    2. Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows)
    3. Select Register to create the application.
  4. In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  5. In the app's registration screen, select the Expose an API blade to the left to open the page where you can publish the permission 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(Application ID URI), follow the following steps:
    1. Select Set next to the Application ID URI to generate a URI that is unique for this app.
    2. For this sample, accept the proposed Application ID URI (https://{tenantName}.onmicrosoft.com/{clientId}) by selecting Save. Read more about Application ID URI at Validation differences by supported account types (signInAudience).
Publish Delegated Permissions
  1. All APIs must publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:
  2. Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
    1. For Scope name, use ToDoList.Read.
    2. For Admin consent display name type in Read users ToDo list using the 'msal-dotnet-api'.
    3. For Admin consent description type in Allow the app to read the user's ToDo list using the 'msal-dotnet-api'.
    4. Keep State as Enabled.
    5. Select the Add scope button on the bottom to save this scope.

    Repeat the steps above for another scope named ToDoList.ReadWrite

  3. Select the Manifest blade on the left.
    1. Set accessTokenAcceptedVersion property to 2.
    2. Select on Save.

ℹ️ Follow the principle of least privilege when publishing permissions for a web API.

Configure the service app (msal-dotnet-api) 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 API\TodoListAPI\appsettings.json file.
  2. Find the key Instance and replace the existing value with your Azure AD B2C tenant name e.g.https://{tenantName}.b2clogin.com.
  3. Find the key ClientId and replace the existing value with the application ID (clientId) of msal-dotnet-api app copied from the Azure portal.
  4. Find the key Domain and replace the existing value with your Azure AD B2C tenant name e.g. {tenantName}.onmicrosoft.com
  5. Find the key SignUpSignInPolicyId and replace the existing value with the user-flow/custom policy Id that you will call this API with e.g. b2c_1_susi (:warning: this should match the policy ID in the default authority in SPA project configuration).

Register the client app (msal-angular-spa)

  1. Navigate to the Azure portal and select the Azure Active Directory 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:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-angular-spa.
    2. Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows)
    3. Select Register to create the application.
  4. In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Single-page application option.
    1. In the Redirect URI section enter the following redirect URIs:
      1. http://localhost:4200
      2. http://localhost:4200/auth
    2. Click Save to save your changes.
  7. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. 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:
    2. Select the Add a permission button and then:
    3. Ensure that the My APIs tab is selected.
    4. In the list of APIs, select the API msal-dotnet-api.
    5. In the Delegated permissions section, select ToDoList.Read, ToDoList.ReadWrite in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.
  8. At this stage, the permissions are assigned correctly, but since it's a B2C tenant, the users themselves cannot consent to these permissions. To get around this problem, we'd let the tenant administrator consent on behalf of all users in the tenant. Select the Grant admin consent for {tenant} button, and then select Yes when you are asked if you want to grant consent for the requested permissions for all accounts in the tenant. You need to be a tenant admin to be able to carry out this operation.
Configure the client app (msal-angular-spa) 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 SPA\src\app\auth-config.ts file.
  2. Find the key msalConfig.clientId and replace the existing value with the application ID (clientId) of msal-angular-spa app copied from the Azure portal.
  3. Find the key protectedResources.scopes.read and replace the existing value with the ToDoList.Read scope you have exposed in the msal-dotnet-api registration steps earlier e.g. https://fabrikamb2c.onmicrosoft.com/TodoList/ToDoList.Read
  4. Find the key protectedResources.scopes.write and replace the existing value with the ToDoList.ReadWrite scope you have exposed in the msal-dotnet-api registration steps earlier e.g. https://fabrikamb2c.onmicrosoft.com/TodoList/ToDoList.ReadWrite

To setup your B2C user-flows, do the following:

  1. Find the key b2cPolicies.names and populate it with your policy names e.g. signUpSignIn.
  2. Find the key b2cPolicies.authorities and populate it with your policy authority strings e.g. https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/b2c_1_susi.
  3. Find the key b2cPolicies.authorityDomain and populate it with the domain portion of your authority string e.g. <your-tenant-name>.b2clogin.com.

Step 6: Running the sample

From your shell or command line, execute the following commands:

    cd SPA
    npm start

Then, open a separate command line and run:

    cd API/TodoListAPI
    dotnet run

Explore the sample

  1. Open your browser and navigate to http://localhost:4200.
  2. Sign-in using the button on the top-right corner.
  3. Select the TodoList button on the navigation bar to access your todo list.

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

ℹ️ if you believe your issue is with the B2C service itself rather than with the sample, please file a support ticket with the B2C team by following the instructions here.

We'd love your feedback!

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

Troubleshooting

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 angular ms-identity adal msal].

If you find a bug in the sample, raise the issue on GitHub Issues.

About the code

CORS settings

You need to set cross-origin resource sharing (CORS) policy to be able to call the TodoListAPI in Startup.cs. For the purpose of the sample, CORS is enabled for all domains and methods. This is insecure and only used for demonstration purposes here. In production, you should modify this as to allow only the domains that you designate. If your web API is going to be hosted on Azure App Service, we recommend configuring CORS on the App Service itself.

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddCors(o => o.AddPolicy("default", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
}

Access token validation

On the web API side, the AddMicrosoftIdentityWebApiAuthentication method in Startup.cs protects the web API by validating access tokens sent tho this API. Check out Protected web API: Code configuration which explains the inner workings of this method in more detail. Simply add the following line under the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // Adds Microsoft Identity platform (AAD v2.0) support to protect this Api
    services.AddMicrosoftIdentityWebApiAuthentication(Configuration);

    // ...
}

For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using jwt.ms.

Verifying permissions

Access tokens that does not have the scp (for delegated permissions) claim with the required scopes/permissions should not be accepted. In the sample, this is illustrated via the RequiredScope attribute in TodoListController.cs:

// GET: api/TodoItems
[HttpGet]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes:Read")]
public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
{
    /// <summary>
    /// The 'oid' (object id) is the only claim that should be used to uniquely identify
    /// a user in an Azure AD tenant. The token might have one or more of the following claim,
    /// that might seem like a unique identifier, but is not and should not be used as such:
    ///
    /// - upn (user principal name): might be unique amongst the active set of users in a tenant
    /// but tend to get reassigned to new employees as employees leave the organization and others
    /// take their place or might change to reflect a personal change like marriage.
    ///
    /// - email: might be unique amongst the active set of users in a tenant but tend to get reassigned
    /// to new employees as employees leave the organization and others take their place.
    /// </summary>
    return await _TodoListContext.TodoItems.Where(x => x.Owner == _currentPrincipalId).ToListAsync();
}

When granting access to data based on scopes, be sure to follow the principle of least privilege.

Debugging the sample

To debug the .NET Core web API that comes with this sample, install the C# extension for Visual Studio Code.

Learn more about using .NET Core with Visual Studio Code.

Next Steps

Learn how to:

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 opencode@microsoft.com with any additional questions or comments.

Learn More