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)
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 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.
You expose a Web API and you want to protect it so that only authenticated user can access it. You want to enable authenticated users with work and school accounts to use your Web API. Your API calls a downstream API (Microsoft Graph) to provide added value to its client apps.
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:
- Signs-in the user.
- Acquires an access token for the Web API.
- 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.
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.
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.
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 Step 2: Register the sample with your Azure Active Directory tenant and Step 3: Configure the sample to use your Azure AD tenant
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you
- modify the Visual Studio projects' configuration files.
If you want to use this automation:
-
On Windows run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Since you've already created an app using the automation earlier, run the following script to clean up the existing registration and prepare your tenant for the additional web API app.
.\AppCreationScripts\Cleanup.ps1
-
Run the script to create your Azure AD applications and configure the code of the sample application accordingly.
.\AppCreationScripts\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts
-
Open the Visual Studio solution and click start
If you don't want to use this automation, follow the steps below
These instructions only list the additional set of steps needed over the previous chapter.
-
Navigate to the Microsoft identity platform for developers App registrations page.
-
Select New registration.
-
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.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
-
Select Register to create the application.
-
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.
-
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
- for Scope name use
- Navigate to the Microsoft identity platform for developers App registrations page.
- 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
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the solution in Visual Studio to configure the projects
Note: if you used the setup scripts, the changes below will have been applied for you
- Open the
TodoListService\appsettings.json
file - Find the app key
Domain
and replace the existing value with your Azure AD tenant name. - Find the app key
TenantId
and replace the existing value with your Azure AD tenant ID. - Find the app key
ClientId
and replace the existing value with the application ID (clientId) of theTodoListService-aspnetcore-webapi
application copied from the Azure portal.
Note: if you used the setup scripts, the changes below will have been applied for you
- Open the
Client\appsettings.json
file - Find the app key
Domain
and replace the existing value with your Azure AD tenant name. - Find the app key
TenantId
and replace the existing value with your Azure AD tenant ID. - Find the app key
ClientId
and replace the existing value with the application ID (clientId) of theTodoListClient-aspnetcore-webapi
application copied from the Azure portal. - Find the app key
ClientSecret
and replace the existing value with the key you saved during the creation of theTodoListClient-aspnetcore-webapi
app, in the Azure portal. - Find the app key
TodoListScope
and replace the existing value with Scope if you changed the name fromapi://<client id>/user_impersonation
. - Find the app key
TodoListBaseAddress
and replace the existing value with the base address of the TodoListService-aspnetcore-webapi project (or use the defaulthttps://localhost:44351/
).
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.
For details about the way the code to sign-in users was created, see Create the sample from command line section, of the README.md file located in the sibling folder named 1. Enable your Web Apps to sign-in users.
In the following section, we will only cover the additional code added to:
- Enable the client app to obtain a token for the web Api.
- Create a new asp.net core Web API project and configure it to secure with Azure AD.
Calling a Web API involves getting a token for this Web API. Acquiring a token is achieved using the MSAL.NET SDK.
Add a reference to the Microsoft.Identity.Client
NuGet package in the TodoListClient project.
Add a reference to the Microsoft.Identity.Web
library if not already present. It contains reusable code that you can use in your Web APIs (and web apps)
- In the TodoListClient project, add a folder named
Models
and then create a new file namedTodoItem.cs
. Copy the contents of the TodoListClient\Models\TodoItem.cs in this file. - Create a new Controller named
TodoListController
and copy and paste the code from the sample (TodoListService\Controllers\TodoListController.cs) to this controller. - Copy the files
TodoListService
andTodoListService.cs
in the TodoListClient\Services folder provided in this sample to your project . - Copy the contents of TodoListClient\views\ToDo folder to the views folder of your project.
- Modify the
Views\Shared\_Layout.cshtml
to add a link to the **ToDolist controller. Check theViews\Shared\_Layout.cshtml
in the sample for reference. - Add a section name TodoList in the appsettings.json file and add the keys
TodoListScope
,TodoListBaseAddress
. - Update the
configureServices
method instartup.cs
to add the MSAL library and a token cache.
services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
.AddMsal(new string[] { Configuration["TodoList:TodoListScope"] })
.AddInMemoryTokenCaches();
The code for the TodoListService was created in the following way:
md TodoListService
cd TodoListService
dotnet new webapi -au=SingleOrg
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.
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
- sets the audiences to validate
- register an issuer validator that accepts issuers to be in the Microsoft identity platform clouds.
- Add the method app.UseAuthentication() before app.UseMvc() in the
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.
- Then add the following code to inject the ToDoList service implementation in the client
// Add APIs
services.AddTodoListService(Configuration);
- Add a folder named
Models
and then create a new file namedTodoItem.cs
. Copy the contents of the TodoListClient\Models\TodoItem.cs in this file. - Create a new Controller named
TodoListController
and copy and paste the code from the sample (\TodoListService\Controllers\TodoListController.cs) to this controller.
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.
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.
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.
For more information, visit the following links:
-
Articles about the new Microsoft identity platform are at http://aka.ms/aaddevv2, with a focus on:
-
To lean more about the application registration, visit:
-
To learn more about the code, visit:
-
To learn more about security in aspnetcore,