Skip to content

Latest commit

 

History

History
313 lines (230 loc) · 17 KB

File metadata and controls

313 lines (230 loc) · 17 KB

Angular single-page application using MSAL Angular to sign-in users with Azure Active Directory and call a .NET Core web API

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. More information
  11. Community Help and Support
  12. Contributing

Overview

This sample demonstrates an Angular single-page application (SPA) calling a ASP.NET Core web API secured with Azure Active Directory (Azure AD) using the Microsoft Authentication Library for Angular (MSAL Angular) for the SPA and the Microsoft.Identity.Web (M.I.W) for the web API.

Scenario

  1. The client Angular SPA uses MSAL Angular to sign-in and obtain a JWT access token from Azure AD.
  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.

Topology

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/appsettings.json Authentication parameters for API project reside here.
API/Startup.cs Microsoft.Identity.Web is initialized here.

Prerequisites

  • An Azure AD tenant. For more information see: How to get an Azure AD tenant
  • A user account in your Azure AD tenant. This sample will not work with a personal Microsoft account. Therefore, if you signed in to the Azure portal with a personal account and have never created a user account in your directory before, you need to do that now.

Setup

Step 1. Clone or download this repository

    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/1-call-api/API
    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

Registration

Register the sample applications with your Azure Active Directory tenant

There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:

  • either follow the steps below for manual registration,
  • or use PowerShell scripts that:
    • automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
    • modify the configuration files.
Expand this section if you want to use this automation:
  1. On Windows, run PowerShell and navigate to the root of the cloned directory

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  4. In PowerShell run:

    cd .\AppCreationScripts\
    .\Configure.ps1

    Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

  5. Follow the section on "Running the sample" below.

Register the service app (msal-dotnet-api)

  1. Navigate to the Azure portal and select the Azure AD service.
  2. 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 msal-dotnet-api.
    • Under Supported account types, select Accounts in this organizational directory only.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. In the app's registration screen, click on 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:
    • Click 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 (api://{clientId}) by selecting Save.
  8. 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.
      • Select Admins and users options for Who can consent?
      • For Admin consent display name type Access msal-dotnet-api
      • For Admin consent description type Allows the app to access msal-dotnet-api as the signed-in user.
      • For User consent display name type Access msal-dotnet-api
      • For User consent description type Allow the application to access msal-dotnet-api on your behalf.
      • Keep State as Enabled
      • Click on the Add scope button on the bottom to save this scope.
  9. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

Configure the service app (msal-dotnet-api) to use your app registration

Open the project in your IDE to configure the code.

In the steps below, "ClientID" is the same as "Application ID" or "AppId".

  1. Open the API\appsettings.json file.

  2. Find the key Domain and replace the existing value with your Azure AD tenant name.

  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 TenantId and replace the existing value with your Azure AD tenant ID.

  5. Open the API\Controllers\TodoListController.cs file.

  6. Find the variable scopeRequiredByApi and replace its value with the name of the API scope that you have just exposed (by default access_as_user).

Register the client app (msal-angular-spa)

  1. Navigate to the Azure portal and select the Azure AD service.
  2. 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 msal-angular-spa.
    • Under Supported account types, select Accounts in this organizational directory only.
    • In the Redirect URI (optional) section, select Single-page application in the combo-box and enter the following redirect URI: http://localhost:4200/.
  4. Select Register to create the application.
  5. 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.
  6. In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
    • Click 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 the access_as_user in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom.

Configure the client app (msal-angular-spa) to use your app registration

Open the project in your IDE 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 Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-angular-spa app copied from the Azure portal.
  3. Find the key Enter_the_Tenant_Info_Here and replace the existing value with your Azure AD tenant ID.
  4. Find the key Enter_the_Web_Api_Scope_here and replace the existing value with scope you created earlier e.g. api://{clientId_of_service_app}/access_as_user.

Run the sample

Using a command line interface such as VS Code integrated terminal, locate the application directory. Then:

    cd SPA
    npm start

In a separate console window, execute the following commands:

    cd API
    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.

We'd love your feedback!

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

About the code

Access token validation

On the SPA side, clients should treat access tokens as opaque strings, as the contents of the token are intended for the resource only (such as a web API or Microsoft Graph). For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.

On the web API side, token validation is handled by Microsoft.Identity.Web, using JwtBearerDefaults.AuthenticationScheme. Simply initialize AddMicrosoftIdentityWebApi() with your configuration and add AddAuthorization() to the service;

        public void ConfigureServices(IServiceCollection services)
        {
            // Setting configuration for protected web api
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(Configuration);

            // Creating policies that wraps the authorization requirements
            services.AddAuthorization();
        }

In your controller, add [Authorize] decorator, which will make sure all incoming requests have an authentication bearer:

    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class TodoListController : ControllerBase
    {
        // The Web API will only accept tokens 1) for users, and 
        // 2) having the access_as_user scope for this API
        static readonly string[] scopeRequiredByApi = new string[] { "access_as_user" };

        private readonly TodoContext _context;

        public TodoListController(TodoContext context)
        {
            _context = context;
        }

        // GET: api/TodoItems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);
            string owner = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            return await _context.TodoItems.Where(item => item.Owner == owner).ToListAsync();
        }
        
        // ...
    }

CORS configuration

You need to set CORS policy to be able to call the TodoListAPI in Startup.cs. For the purpose of this sample, we are setting it to allow any domain and methods. In production, you should modify this to allow only the domains and methods you designate.

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

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.

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