Skip to content
Branch: master
Find file History

README.md

services platforms author level client service endpoint
active-directory
dotnet
kalyankrishna1
200
ASP.NET Core Web App
ASP.NET Core Web API
Microsoft identity platform

How to secure a Web API built with ASP.NET Core using the Microsoft identity platform (formerly Azure Active Directory for developers)

Build status

The sample in this folder is part of a multi-chapter tutorial. The first phase is available at An ASP.NET Core Web app signing-in users with the Microsoft identity platform in your organization.

This article (README.md) contains the full instructions on how to configure the sample. If you have gone through the first chapter and already configured the client web application to sigh-in users, read through the README-incremental-instructions.md instead.

About this sample

This sample is essentially a guide for developers who want to secure their Web APIs using the Microsoft identity platform (formerly Azure Active Directory for developers). This sample lays down the all the steps developers need to take to secure their web api with the Microsoft identity platform. Additionally it also explains the steps and processes for a client to obtain the necessary permissions and tokens to make successful calls to this secured web api.

Scenario

This sample has a web api and a client web app, both built using the asp.net core platform. The client app signs in users using the OpenID Connect protocol flow and in this process obtains (and caches) an access token for the web api. The client app has a ToDo list that the web app users can work with. This ToDo list is maintained in an in-memory list on the Web API. The client app calls the webApi for all operations on the ToDo list.

Overview

This sample presents a Web API running on ASP.NET Core, protected by Azure AD OAuth Bearer Authentication. The client application uses MSAL.NET library to obtain a JWT access token through using the OAuth 2.0 protocol flow.

The client web application essentially takes the following steps to sign-in the user and obtain a bearer token for the Web API:

  1. Signs-in the user. When the user signs-in for the first time , a consent screen is presented. This consent screen lets the user consent for the application to access the web API( TodoListService).
  2. Acquires an access token for the Web API.
  3. Calls the Web API using the access token as a bearer token in the authentication header of the Http request. The Web API validates the caller using the ASP.NET JWT Bearer Authentication middleware.

Topology

The end user experience when using this sample

The Web API (TodoListService) maintains an in-memory collection of to-do items per authenticated user. Multiple client applications signing-in users under the same identities, will share the same to-do list.

The client web application (TodoListClient) enables a user to:

  • Sign in to the client app.
  • After the sign-in, the user sees the list of to-do items exposed by Web API for the signed-in user.
  • The user can add/edit/delete to-do items by clicking on the various options presented.

How to run this sample

Pre-requisites

  • Install .NET Core for Windows by following the instructions at dot.net/core, which will include Visual Studio 2017.
  • An Internet connection
  • An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant
  • A user account in your Azure AD tenant.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2.git

cd "4-WebApp-your-API\4-1-Your-API"

or download and exact the repository .zip file.

Given that the name of the sample is pretty long, and so are the name of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Step 2: Register the sample application 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:

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.

    cd .\AppCreationScripts\ 
    .\Configure.ps1

    Other ways of running the scripts are described in App Creation Scripts

  4. Open the Visual Studio solution and click start

If you don't want to use this automation, follow the steps below.

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 using either a work or school account or a personal Microsoft account.
  2. If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.

Register the service app (TodoListService-aspnetcore-webapi)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. When the Register an application page 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-webapi.
    • Leave Supported account types on the default setting of Accounts in this organizational directory only.
  4. Select Register to create the application.

  5. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.

  6. Select the Expose an API section, and:

    • Select Add a scope
    • accept the proposed Application ID URI (api://{clientId}) by selecting Save and Continue
    • Enter the following parameters
      • for Scope name use user_impersonation
      • Keep Admins and users for Who can consent
      • in Admin consent display name type Access TodoListService-aspnetcore-webapi as a user
      • in Admin consent description type Accesses the TodoListService-aspnetcore-webapi Web API as a user
      • in User consent display name type Access TodoListService-aspnetcore-webapi as a user
      • in User consent description type Accesses the TodoListService-aspnetcore-webapi Web API as a user
      • Keep State as Enabled
      • Select Add scope

Register the client app (TodoListClient-aspnetcore-webapi)

  1. Navigate to the Microsoft identity platform for developers App registrations page.

  2. Select New registration.

  3. When the Register an application page 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 TodoListClient-aspnetcore-webapi.
    • Leave Supported account types on the default setting of Accounts in this organizational directory only.

      Note that there are more than one redirect URIs. You'll need to add them from the Authentication tab later after the app has been created successfully.

  4. Select Register to create the application.

  5. On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.

  6. From the app's Overview page, select the Authentication section.

    • In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.
      • https://localhost:44321/
      • https://localhost:44321/signin-oidc
    • In the Advanced settings section set Logout URL to https://localhost:44321/signout-oidc
    • In the Advanced settings | Implicit grant section, check ID tokens as this sample requires the Implicit grant flow to be enabled to sign-in the user, and call an API.
  7. Select Save.

  8. From the Certificates & secrets page, in the Client secrets section, choose New client secret:

    • Type a key description (of instance app secret),
    • Select a key duration of either In 1 year, In 2 years, or Never Expires.
    • When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
    • You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
  9. Select the API permissions section

    • Click 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-webapi.
    • In the Delegated permissions section, ensure that the right permissions are checked: Access 'TodoListService-aspnetcore-webapi'. Use the search box if necessary.
    • Select the Add permissions button

Step 3: Configure the sample to use your Azure AD tenant

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

Open the solution in Visual Studio to configure the projects

Configure the service project

Note: if you had used the automation to setup your application mentioned in Step 2: Register the sample application with your Azure Active Directory tenant, the changes below would have been applied by the scripts.

  1. Open the TodoListService\appsettings.json file
  2. Find the app key Domain and replace the existing value with your Azure AD tenant name.
  3. Find the app key TenantId and replace the existing value with your Azure AD tenant ID.
  4. Find the app key ClientId and replace the existing value with the application ID (clientId) of the TodoListService-aspnetcore-webapi application copied from the Azure portal.

Configure the client project

Note: if you had used the automation to setup your application mentioned in Step 2: Register the sample application with your Azure Active Directory tenant, the changes below would have been applied by the scripts.

  1. Open the Client\appsettings.json file
  2. Find the app key Domain and replace the existing value with your Azure AD tenant name.
  3. Find the app key TenantId and replace the existing value with your Azure AD tenant ID.
  4. Find the app key ClientId and replace the existing value with the application ID (clientId) of the TodoListClient-aspnetcore-webapi application copied from the Azure portal.
  5. Find the app key ClientSecret and replace the existing value with the key you saved during the creation of the TodoListClient-aspnetcore-webapi app, in the Azure portal.
  6. Find the app key TodoListScope and replace the existing value with Scope if you changed the name from api://<client id>/user_impersonation.
  7. Find the app key TodoListBaseAddress and replace the existing value with the base address of the TodoListService-aspnetcore-webapi project (or use the default https://localhost:44351).

Step 4: Run the sample

Clean the solution, rebuild the solution, and run it. You will have 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 (case with Microsoft Edge)
  • or an error HTTP 401 (case with Chrome)

This behavior is expected as you are not authenticated. The client application will be authenticated, so it will be able to access the Web API.

Explore the sample by signing in into the TodoList client, adding items to the To Do list. If you stop the application without signing out, the next time you run the application, you won't be prompted to sign in again.

NOTE: Remember, the To-Do list is stored in memory in this TodoListService app. Each time you run the projects, your To-Do list will get emptied.

Did the sample not work for you as expected? Did you encounter issues trying this sample? Then please reach out to us using the GitHub Issues page.

How was the code created

Creating the client web app (TodoListClient)

Step 1: Create the sample from the command line

  1. Run the following command to create a sample from the command line using the SingleOrg template:

    md TodoListClient
    cd TodoListClient
    dotnet new mvc --auth SingleOrg --client-id <Enter_the_Application_Id_here> --tenant-id <yourTenantId>

    Note: Replace Enter_the_Application_Id_here with the Application Id from the application Id you just registered in the Application Registration Portal and <yourTenantId> with the Directory (tenant) ID where you created your application.

Step 2: Modified the generated code

  1. Open the generated project (.csproj) in Visual Studio, and save the solution.

  2. Add the Microsoft.Identity.Web.csproj project which is located at the root of this sample repo, to your solution (Add Existing Project ...). It's used to simplify signing-in and, in the next tutorial phases, to get a token.

  3. Add a reference from your newly generated project to Microsoft.Identity.Web (right click on the Dependencies node under your new project, and choose Add Reference ..., and then in the projects tab find the Microsoft.Identity.Web project)

  4. Open the Startup.cs file and:

    • at the top of the file, add the following using directive:

       using Microsoft.Identity.Web;
    • in the ConfigureServices method, replace the two following lines:

       services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
               .AddAzureAD(options => Configuration.Bind("AzureAd", options));

      by this line:

      services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
           .AddMsal(new string[] { Configuration["TodoList:TodoListScope"] })
           .AddInMemoryTokenCaches();

      This enables your application to use the Microsoft identity platform endpoint. This endpoint is capable of signing-in users both with their Work and School and Microsoft Personal accounts.

    1. Change the Properties\launchSettings.json file to ensure that you start your web app from https://localhost:44321 as registered. For this:
    • update the sslPort of the iisSettings section to be 44321
    • in the applicationUrl property of use https://localhost:44321
  • Then add the following code to inject the ToDoList service implementation in the client
  // Add APIs
  services.AddTodoListService(Configuration);
  1. Open the appsettings.json file and copy the keys from the sample's corresponding file under the AzureAd and TodoList sections.

Add a model (TodoListItem) and add the controller and views

  1. In the TodoListClient project, add a folder named Models and then create a new file named TodoItem.cs. Copy the contents of the TodoListClient\Models\TodoItem.cs in this file.

  2. Create a new Controller named TodoListController and copy and paste the code from the sample (TodoListService\Controllers\TodoListController.cs) to this controller.

  3. Copy the files TodoListService and TodoListService.cs in the TodoListClient\Services folder provided in this sample to your project .

  4. Copy the contents of TodoListClient\views\ToDo folder to the views folder of your project.

  5. Modify the Views\Shared\_Layout.cshtml to add a link to the **ToDolist controller. Check the Views\Shared\_Layout.cshtml in the sample for reference.

  6. Add a section name TodoList in the appsettings.json file and add the keys TodoListScope, TodoListBaseAddress.

  7. Update the configureServices method in startup.cs to add the MSAL library and a token cache.

     services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
          .AddMsal(new string[] { Configuration["TodoList:TodoListScope"] })
          .AddInMemoryTokenCaches();
  8. Update the Configure method to include app.UseAuthentication(); before app.UseMvc();

   app.UseAuthentication();
   app.UseMvc();

Creating the Web API project (TodoListService)

The code for the TodoListService was created in the following way:

Step 1: Create the web api using the ASP.NET Core templates

md TodoListService
cd TodoListService
dotnet new webapi -au=SingleOrg
  1. Open the generated project (.csproj) in Visual Studio, and save the solution.

Add a model (TodoListItem) and modify the controller

In the TodoListService project, add a folder named Models and then create a new file named TodoItem.cs. Copy the contents of the TodoListService\Models\TodoItem.cs in this file.

Modify the Startup.cs file to validate bearer access tokens received by the Web API

  1. Add the Microsoft.Identity.Web.csproj project which is located at the root of this sample repo, to your solution (Add Existing Project ...).
  2. Add a reference from your newly generated project to Microsoft.Identity.Web (right click on the Dependencies node under your new project, and choose Add Reference ..., and then in the projects tab find the Microsoft.Identity.Web project) Update Startup.cs file :
  • Add the following two using statements
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Client.TokenCacheProviders;
  • In the ConfigureServices method, replace the following code:

    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

    with

      services.AddProtectedWebApi(Configuration)
           .AddInMemoryTokenCaches();
  • Add the method app.UseAuthentication() before app.UseMvc() in the Configure method

       app.UseAuthentication();
       app.UseMvc();

    AddProtectedWebApi does the following:

    • add the JwtBearerAuthenticationScheme (Note the replacement of BearerAuthenticationScheme by JwtBearerAuthenticationScheme)
    • set the authority to be the Microsoft identity platform identity
    • sets the audiences to validate
    • register an issuer validator that accepts issuers to be in the Microsoft identity platform clouds.

The implementations of these classes are in the Microsoft.Identity.Web library (and folder), and they are designed to be reusable in your applications (Web apps and Web apis). You are encouraged to browse the code in the library to understand the changes in detail.

Create the TodoListController.cs file

  1. Add a folder named Models and then create a new file named TodoItem.cs. Copy the contents of the TodoListClient\Models\TodoItem.cs in this file.
  2. Create a new Controller named TodoListController and copy and paste the code from the sample (\TodoListService\Controllers\TodoListController.cs) to this controller.

How to deploy this sample to Azure

This project has two WebApp / Web API projects. To deploy them to Azure Web Sites, you'll need, for each one, to:

  • create an Azure Web Site
  • publish the Web App / Web APIs to the web site, and
  • update its client(s) to call the web site instead of IIS Express.

Create and publish the TodoListService-aspnetcore-webapi to an Azure Web Site

  1. Sign in to the Azure portal.
  2. Click Create a resource in the top left-hand corner, select Web --> Web App, and give your web site a name, for example, TodoListService-aspnetcore-webapi-contoso.azurewebsites.net.
  3. Thereafter select the Subscription, Resource Group, App service plan and Location. OS will be Windows and Publish will be Code.
  4. Click Create and wait for the App Service to be created.
  5. Once you get the Deployment succeeded notification, then click on Go to resource to navigate to the newly created App service.
  6. Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
  7. From the Overview tab of the App Service, download the publish profile by clicking the Get publish profile link and save it. Other deployment mechanisms, such as from source control, can also be used.
  8. Switch to Visual Studio and go to the TodoListService-aspnetcore-webapi project. Right click on the project in the Solution Explorer and select Publish. Click Import Profile on the bottom bar, and import the publish profile that you downloaded earlier.
  9. Click on Configure and in the Connection tab, update the Destination URL so that it is a https in the home page url, for example https://TodoListService-aspnetcore-webapi-contoso.azurewebsites.net. Click Next.
  10. On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Save. Click on Publish on the main screen.
  11. Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.

Update the Active Directory tenant application registration for TodoListService-aspnetcore-webapi

  1. Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).
  2. In the resultant screen, select the TodoListService-aspnetcore-webapi application.
  3. From the Branding menu, update the Home page URL, to the address of your service, for example https://TodoListService-aspnetcore-webapi-contoso.azurewebsites.net. Save the configuration.
  4. Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.

Update the TodoListClient-aspnetcore-webapi to call the TodoListService-aspnetcore-webapi Running in Azure Web Sites

  1. In Visual Studio, go to the TodoListClient-aspnetcore-webapi project.
  2. Open Client\appsettings.json. Only one change is needed - update the todo:TodoListBaseAddress key value to be the address of the website you published, for example, https://TodoListService-aspnetcore-webapi-contoso.azurewebsites.net.
  3. Run the client! If you are trying multiple different client types (for example, .Net, Windows Store, Android, iOS) you can have them all call this one published web API.

Create and publish the TodoListClient-aspnetcore-webapi to an Azure Web Site

  1. Sign in to the Azure portal.
  2. Click Create a resource in the top left-hand corner, select Web --> Web App, and give your web site a name, for example, TodoListClient-aspnetcore-webapi-contoso.azurewebsites.net.
  3. Thereafter select the Subscription, Resource Group, App service plan and Location. OS will be Windows and Publish will be Code.
  4. Click Create and wait for the App Service to be created.
  5. Once you get the Deployment succeeded notification, then click on Go to resource to navigate to the newly created App service.
  6. Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
  7. From the Overview tab of the App Service, download the publish profile by clicking the Get publish profile link and save it. Other deployment mechanisms, such as from source control, can also be used.
  8. Switch to Visual Studio and go to the TodoListClient-aspnetcore-webapi project. Right click on the project in the Solution Explorer and select Publish. Click Import Profile on the bottom bar, and import the publish profile that you downloaded earlier.
  9. Click on Configure and in the Connection tab, update the Destination URL so that it is a https in the home page url, for example https://TodoListClient-aspnetcore-webapi-contoso.azurewebsites.net. Click Next.
  10. On the Settings tab, make sure Enable Organizational Authentication is NOT selected. Click Save. Click on Publish on the main screen.
  11. Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.

Update the Active Directory tenant application registration for TodoListClient-aspnetcore-webapi

  1. Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).
  2. In the resultant screen, select the TodoListClient-aspnetcore-webapi application.
  3. In the Authentication | page for your application, update the Logout URL fields with the address of your service, for example https://TodoListClient-aspnetcore-webapi-contoso.azurewebsites.net
  4. From the Branding menu, update the Home page URL, to the address of your service, for example https://TodoListClient-aspnetcore-webapi-contoso.azurewebsites.net. Save the configuration.
  5. Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.

NOTE: Remember, the To Do list is stored in memory in this TodoListService sample. Azure Web Sites will spin down your web site if it is inactive, and your To Do list will get emptied. Also, if you increase the instance count of the web site, requests will be distributed among the instances. To Do will, therefore, not be the same on each instance.

Next steps

If you're interested in the Web API calling a downstream API, you might want to have a look at the ASP.NET Core Web API tutorial, in chapter 2 2. Web API now calls Microsoft Graph/. The client is a desktop app there, whereas you have a Web App, but apart from that all the app registration steps apply.

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 [msal dotnet azure-active-directory].

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

To provide a recommendation, visit the following 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.

More information

For more information, visit the following links:

You can’t perform that action at this time.