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 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.
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.
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.
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. 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).
- 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.
- 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.
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
-
Run the script to create your Azure AD application 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.
As a first step you'll need to:
- Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
- 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.
-
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 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
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.
- 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.
-
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.
- In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.
-
Select Save.
-
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.
- Type a key description (of instance
-
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 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.
- 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 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.
- 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.
-
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.
-
Open the generated project (.csproj) in Visual Studio, and save the solution.
-
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. -
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 theMicrosoft.Identity.Web
project) -
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.
- 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 theiisSettings
section to be44321
- in the
applicationUrl
property of usehttps://localhost:44321
-
- Then add the following code to inject the ToDoList service implementation in the client
// Add APIs
services.AddTodoListService(Configuration);
- Open the
appsettings.json
file and copy the keys from the sample's corresponding file under theAzureAd
andTodoList
sections.
-
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();
-
Update the
Configure
method to include app.UseAuthentication(); before app.UseMvc();
app.UseAuthentication();
app.UseMvc();
The code for the TodoListService was created in the following way:
md TodoListService
cd TodoListService
dotnet new webapi -au=SingleOrg
- Open the generated project (.csproj) in Visual Studio, and save the solution.
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.
- Add the
Microsoft.Identity.Web.csproj
project which is located at the root of this sample repo, to your solution (Add Existing Project ...). - 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 theMicrosoft.Identity.Web
project) UpdateStartup.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
methodapp.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.
- 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.
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.
- Sign in to the Azure portal.
- 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
. - Thereafter select the
Subscription
,Resource Group
,App service plan and Location
.OS
will be Windows andPublish
will be Code. - Click
Create
and wait for the App Service to be created. - Once you get the
Deployment succeeded
notification, then click onGo to resource
to navigate to the newly created App service. - Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
- 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.
- 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.
- Click on Configure and in the
Connection tab
, update the Destination URL so that it is ahttps
in the home page url, for example https://TodoListService-aspnetcore-webapi-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authentication
is NOT selected. Click Save. Click on Publish on the main screen. - 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.
- 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).
- In the resultant screen, select the
TodoListService-aspnetcore-webapi
application. - 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.
- 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
- In Visual Studio, go to the
TodoListClient-aspnetcore-webapi
project. - Open
Client\appsettings.json
. Only one change is needed - update thetodo:TodoListBaseAddress
key value to be the address of the website you published, for example, https://TodoListService-aspnetcore-webapi-contoso.azurewebsites.net. - 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.
- Sign in to the Azure portal.
- 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
. - Thereafter select the
Subscription
,Resource Group
,App service plan and Location
.OS
will be Windows andPublish
will be Code. - Click
Create
and wait for the App Service to be created. - Once you get the
Deployment succeeded
notification, then click onGo to resource
to navigate to the newly created App service. - Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
- 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.
- 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.
- Click on Configure and in the
Connection tab
, update the Destination URL so that it is ahttps
in the home page url, for example https://TodoListClient-aspnetcore-webapi-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authentication
is NOT selected. Click Save. Click on Publish on the main screen. - 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.
- 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).
- In the resultant screen, select the
TodoListClient-aspnetcore-webapi
application. - 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
- 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.
- 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.
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 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,