| 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 |
|
||||||||||||
| products |
|
||||||||||||
| urlFragment | spa-msal-angular-b2c-netcore | ||||||||||||
| extensions |
|
Angular single-page application that authenticates users with Azure AD B2C and calls a protected .NET Core web API
- Overview
- Scenario
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Steps
- Contributing
- Learn More
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
- The client Angular SPA uses MSAL Angular to sign-in a user 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 the .NET Core web API protected by Azure AD B2C.
- The service uses the Microsoft.Identity.Web to protect the Web api, check permissions and validate tokens.
| 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. |
- Either Visual Studio or Visual Studio Code and .NET Core SDK
- 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:
git clone https://github.com/Azure-Samples/ms-identity-javascript-angular-tutorial.gitor 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.
cd ms-identity-javascript-angular-tutorial
cd 3-Authorization-II/2-call-api-b2c/API/TodoListAPI
dotnet restore dotnet dev-certs https --clean
dotnet dev-certs https --trustFor more information and potential issues, see: HTTPS in .NET Core.
cd ../
cd SPA
npm install
⚠️ 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.
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 Active Directory 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
msal-dotnet-api. - Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows)
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- 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.
- 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:
- 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. Read more about Application ID URI at Validation differences by supported account types (signInAudience).
- 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:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
ToDoList.Read. - For Admin consent display name type in Read users ToDo list using the 'msal-dotnet-api'.
- For Admin consent description type in Allow the app to read the user's ToDo list using the 'msal-dotnet-api'.
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
Repeat the steps above for another scope named ToDoList.ReadWrite
- For Scope name, use
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersionproperty to 2. - Select on Save.
- Set
ℹ️ Follow the principle of least privilege when publishing permissions for a web API.
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
API\TodoListAPI\appsettings.jsonfile. - Find the key
Instanceand replace the existing value with your Azure AD B2C tenant name e.g.https://{tenantName}.b2clogin.com. - Find the key
ClientIdand replace the existing value with the application ID (clientId) ofmsal-dotnet-apiapp copied from the Azure portal. - Find the key
Domainand replace the existing value with your Azure AD B2C tenant name e.g.{tenantName}.onmicrosoft.com - Find the key
SignUpSignInPolicyIdand 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).
- Navigate to the Azure portal and select the Azure Active Directory 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
msal-angular-spa. - Under Supported account types, select Accounts in any identity provider or organizational directory (for authenticating users with user flows)
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- 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.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URIs:
http://localhost:4200http://localhost:4200/auth
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- 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
msal-dotnet-api. - In the Delegated permissions section, select ToDoList.Read, ToDoList.ReadWrite in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- 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.
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
SPA\src\app\auth-config.tsfile. - Find the key
msalConfig.clientIdand replace the existing value with the application ID (clientId) ofmsal-angular-spaapp copied from the Azure portal. - Find the key
protectedResources.scopes.readand replace the existing value with theToDoList.Readscope you have exposed in themsal-dotnet-apiregistration steps earlier e.g.https://fabrikamb2c.onmicrosoft.com/TodoList/ToDoList.Read - Find the key
protectedResources.scopes.writeand replace the existing value with theToDoList.ReadWritescope you have exposed in themsal-dotnet-apiregistration steps earlier e.g.https://fabrikamb2c.onmicrosoft.com/TodoList/ToDoList.ReadWrite
To setup your B2C user-flows, do the following:
- Find the key
b2cPolicies.namesand populate it with your policy names e.g.signUpSignIn. - Find the key
b2cPolicies.authoritiesand populate it with your policy authority strings e.g.https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/b2c_1_susi. - Find the key
b2cPolicies.authorityDomainand populate it with the domain portion of your authority string e.g.<your-tenant-name>.b2clogin.com.
From your shell or command line, execute the following commands:
cd SPA
npm startThen, open a separate command line and run:
cd API/TodoListAPI
dotnet run- Open your browser and navigate to
http://localhost:4200. - Sign-in using the button on the top-right corner.
- 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.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
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.
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();
}));
}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.
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.
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.
Learn how to:
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.
- 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
- Building Zero Trust ready apps
- Microsoft.Identity.Web
- Validating Access Tokens
- User and application tokens
- Validation differences by supported account types
- How to manually validate a JWT access token using the Microsoft identity platform
