page_type | languages | products | name | urlFragment | services | platforms | author | level | client | service | endpoint | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
|
|
How to manually validate a JWT access token using the Microsoft identity platform |
active-directory-dotnet-webapi-manual-jwt-validation |
active-directory |
dotnetcore |
kalyankrishna1 |
300 |
.NET Desktop App (WPF) |
ASP.NET Web API |
AAD v2.0 |
- Overview
- About this sample
- Scenario: protecting a Web API - acquiring a token for the protected Web API
- Prerequisites
- Setup
- Running the sample
- Explore the sample
- About The Code
- How To Recreate This Sample
- How to deploy this sample to Azure
- Azure Government Deviations
- Troubleshooting
- Community Help and Support
- Contributing
- More information
This sample demonstrates how to manually validate an access token issued to a web API protected by the Microsoft Identity Platform. Here a .NET Desktop App (WPF) calls a protected ASP.NET Web API that is secured using Azure AD.
A Web API that accepts bearer token as a proof of authentication is secured by validating the token they receive from the callers. When a developer generates a skeleton Web API code using Visual Studio, token validation libraries and code to carry out basic token validation is automatically generated for the project. An example of the generated code using the asp.net security middleware and Microsoft Identity Model Extension for .NET to validate tokens is provided below.
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}
The code above will validate the issuer, audience, and the signing tokens of the access token, which is usually sufficient for most scenarios. But often the developer's requirements are more than what these defaults provide. Examples of these requirements can be:
- Restricting the Web API to one or more Apps (App IDs)
- Restricting the Web API to just one or more tenants (Issuers)
- Implement custom authorization.
Always verify that the access token presented to the Web Api has the expected scopes or roles
This sample demonstrates how to manually process a JWT access token in a web API using the JSON Web Token Handler For the Microsoft .Net Framework. This sample is equivalent to the NativeClient-DotNet sample, except that, in the TodoListService
, instead of using OWIN middleware to process the token, the token is processed manually in application code. The client, which demonstrates how to acquire a token for this protected API, is unchanged from the NativeClient-DotNet sample.
When you want to protect a Web API, you request your clients to get a Security token for your API, and you validate it. Usually, for ASP.NET applications this validation is delegated to the OWIN middleware, but you can also validate it yourself, leveraging the System.IdentityModel.Tokens.Jwt
library.
A token represents the outcome of an authentication operation with some artifact that can be unambiguously tied to the Identity Provider that performed the authentication, without relying on any special network infrastructure.
With Azure Active Directory taking the full responsibility of verifying user's raw credentials, the token receiver's responsibility shifts from verifying raw credentials to verifying that their caller did indeed go through your identity provider of choice and successfully authenticated. The identity provider represents successful authentication operations by issuing a token, hence the job now becomes to validate that token.
While you should always validate tokens issued to the resources (audience) that you are developing, your application will also obtain access tokens for other resources from AAD. AAD will provide an access token in whatever token format that is appropriate to that resource. This access token itself should be treated like an opaque blob by your application, as your app isn’t the access token’s intended audience and thus your app should not bother itself with looking into the contents of this access token. Your app should just pass it in the call to the resource. It's the called resource's responsibility to validate this access token.
When an application receives an access token upon user sign-in, it should also perform a few checks against the claims in the access token. These verifications include but are not limited to:
- audience claim, to verify that the ID token was intended to be given to your application
- not before and "expiration time" claims, to verify that the ID token has not expired
- issuer claim, to verify that the token was issued to your app by the v2.0 endpoint
- nonce, as a token replay attack mitigation
You are advised to use standard library methods like JwtSecurityTokenHandler.ValidateToken Method (JwtSecurityToken) to do most of the aforementioned heavy lifting. You can further extend the validation process by making decisions based on claims received in the token. For example, multi-tenant applications can extend the standard validation by inspecting the value of the tid
claim (Tenant ID) against a set of pre-selected tenants to ensure they only honor tokens from tenants of their choice. Details on the claims provided in JWT tokens are listed in the Azure AD token reference. When you debug your application and want to understand the claims held by the token, you might find it useful to use the JWT token inspector tool.
Looking for previous versions of this code sample? Check out the tags on the releases GitHub page.
[!Note] If you want to run this sample on Azure Government, navigate to the "Azure Government Deviations" section at the bottom of this page.
- Visual Studio
- 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. If you're signed in to the Azure portal with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation.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.
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- follow the steps below for manually register your apps
- 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.
Expand this section if you want to use this automation:
⚠️ If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
On Windows, run PowerShell as Administrator and navigate to the root of the cloned directory
-
If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.
-
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.
-
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.
-
Open the Visual Studio solution and click start to run the code.
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 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 tenant.
- Navigate to the Azure portal and select the Azure AD 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
TodoListService-ManualJwt
. - Under Supported account types, select 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.
- 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.
- Select Save to save your changes.
- In the app's registration screen, select 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:
- 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 (
api://{clientId}
) by selecting Save.
- Select
- 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 these 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 TodoListService-ManualJwt
. - For Admin consent description type
Allows the app to access TodoListService-ManualJwt as the signed-in user.
- For User consent display name type
Access TodoListService-ManualJwt
. - For User consent description type
Allow the application to access TodoListService-ManualJwt on your behalf.
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- Select the
Manifest
blade on the left.- Set
accessTokenAcceptedVersion
property to 2. - Click on Save.
- Set
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
TodoListService-ManualJwt\Web.Config
file. - Find the key
ida:TenantId
and replace the existing value with your Azure AD tenant ID. - Find the key
ida:Audience
and replace the existing value with the App ID URI you registered earlier, when exposing an API. For instance useapi://<application_id>
. - Find the key
ida:ClientId
and replace the existing value with the application ID (clientId) ofTodoListService-ManualJwt
app copied from the Azure portal.
- Navigate to the Azure portal and select the Azure AD 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
TodoListClient-ManualJwt
. - Under Supported account types, select 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.
- 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.
- In the app's registration screen, select Authentication in the menu.
- If you don't have a platform added, select Add a platform and select the Public client (mobile & desktop) option.
- In the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, select https://login.microsoftonline.com/common/oauth2/nativeclient
- Select Save to save your changes.
- 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
TodoListService-ManualJwt
. - In the Delegated permissions section, select the Access 'TodoListService-ManualJwt' in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
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
TodoListClient\App.Config
file. - Find the key
ida:Tenant
and replace the existing value with your Azure AD tenant name. - Find the key
ida:ClientId
and replace the existing value with the application ID (clientId) ofTodoListClient-ManualJwt
app copied from the Azure portal. - Find the key
todo:TodoListResourceId
and replace the existing value with the App ID URI you registered earlier, when exposing an API. For instance useapi://<application_id>
. - Find the key
todo:TodoListBaseAddress
and replace the existing value with the base address ofTodoListService-ManualJwt
(by defaulthttps://localhost:44324
).
For Visual Studio Users
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with the service project starting first.
Explore the sample by signing in, adding items to the To Do list, removing the user account, and starting again. Notice that if you stop the application without removing the user account, the next time you run the application you won't be prompted to sign in again - that is the sample implements a persistent cache for MSAL, and remembers the tokens from the previous run.
ℹ️ 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.
The manual JWT validation occurs in the TokenValidationHandler implementation in the Global.aspx.cs
file in the TodoListService-ManualJwt project.
Each time a call is made to the web API, the TokenValidationHandler.SendAsync() handler is executed:
This method:
- Gets the token from the Authorization headers
- Gets the open ID configuration, including keys from the Azure AD discovery endpoint
- Sets the parameters to validate in
GetTokenValidationParameters()
- the audience - the application accepts both its App ID URI and its AppID/clientID
- the valid issuers - the application accepts both Azure AD V1 and Azure AD V2
- Then the token is validated
- An asp.net claims principal is created after a successful validation
- ensures that the web API is consented to and provisioned in the Azure AD tenant from where the access token originated
- Finally, a check for scopes that the web API expects from the caller is carried out
The TokenValidationHandler
class is registered with ASP.NET in the TodoListService-ManualJwt/Global.asx.cs
file, in the Application_Start() method.
For more validation options, please refer to TokenValidationParameters.cs
If you do not wish to control the token validation from its very beginning to the end as laid out in the Global.asax.cs
, but only limit yourself to validate business logic based on claims in the presented token, you can craft a Custom token handler as provided in the example below.
The provided example, validates to allow callers from a list of whitelisted tenants only.
- Create a custom handler implementation
public class CustomTokenHandler : JwtSecurityTokenHandler
{
public override ClaimsPrincipal ValidateToken(
string token, TokenValidationParameters validationParameters,
out SecurityToken validatedToken)
{
try
{
var claimsPrincipal = base.ValidateToken(token, validationParameters, out validatedToken);
string[] allowedTenants = { "14c2f153-90a7-4689-9db7-9543bf084dad", "af8cc1a0-d2aa-4ca7-b829-00d361edb652", "979f4440-75dc-4664-b2e1-2cafa0ac67d1" };
string tenantId = claimsPrincipal.Claims.FirstOrDefault(x => x.Type == "tid" || x.Type == "http://schemas.microsoft.com/identity/claims/tenantid")?.Value;
if (!allowedTenants.Contains(tenantId))
{
throw new Exception("This tenant is not authorized");
}
return claimsPrincipal;
}
catch (Exception e)
{
throw;
}
}
}
- Assign the custom handler in
Startup.Auth.cs
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
TokenHandler = new CustomTokenHandler()
});
First, in Visual Studio 2017 create an empty solution to host the projects. Then, follow these steps to create each project.
-
In Visual Studio, create a new
Visual C#
ASP.NET Web Application (.NET Framework)
. ChooseWeb Api
in the next screen. Leave the project's chosen authentication mode as the default, that is,No Authentication
". -
Set SSL Enabled to be True. Note the SSL URL.
-
In the project properties, Web properties, set the Project Url to be the SSL URL.
-
Add the latest stable JSON Web Token Handler For the Microsoft .Net Framework NuGet, System.IdentityModel.Tokens.Jwt, to the project.
-
Add an assembly reference to
System.IdentityModel
. -
In the
Models
folder, add a new class namedTodoItem.cs
. Copy the implementation of TodoItem from this sample into the class. -
Create a folder named
Utils
, add a new class namedClaimConstants.cs
. Copy the implementation ofClaimConstants.cs
from this sample into the class. -
Add a new, empty, Web API 2 controller named
TodoListController
. -
Copy the implementation of the TodoListController from this sample into the controller.
-
Open Global.asax, and copy the implementation from this sample into the controller. Note that a single line is added at the end of
Application_Start()
,GlobalConfiguration.Configuration.MessageHandlers.Add(new TokenValidationHandler());
-
In
web.config
create keys forida:AADInstance
,ida:Tenant
, andida:Audience
and set them accordingly. For the global Azure cloud, the value ofida:AADInstance
ishttps://login.microsoftonline.com/{0}
.
- In the solution, create a new Windows --> Windows Classic Desktop -> WPF App(.NET Framework) called TodoListClient.
- Add the Microsoft Authentication Library (MSAL) NuGet,
Microsoft.Identity.Client
to the project. - Add assembly references to
System.Net.Http
,System.Web.Extensions
, andSystem.Configuration
. - Add a new class to the project named
TodoItem.cs
. Copy the code from the sample project file of the same name into this class, completely replacing the code in the file in the new project. - Add a new class to the project named
FileCache.cs
. Copy the code from the sample project file of the same name into this class, completely replacing the code in the file in the new project. - Copy the markup from
MainWindow.xaml
in the sample project into the file of the same name in the new project, completely replacing the markup in the file in the new project. - Copy the code from
MainWindow.xaml.cs
in the sample project into the file of the same name in the new project, completely replacing the code in the file in the new project. - In
app.config
create keys forida:AADInstance
,ida:Tenant
,ida:ClientId
,todo:TodoListResourceId
, andtodo:TodoListBaseAddress
and set them accordingly. For the global Azure cloud, the value ofida:AADInstance
ishttps://login.microsoftonline.com/{0}
.
Finally, in the properties of the solution itself, set both projects as startup projects.
This project has one 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-ManualJwt-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. -
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-ManualJwt 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-ManualJwt-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-ManualJwt
application. - From the Branding menu, update the Home page URL, to the address of your service, for example https://TodoListService-ManualJwt-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-ManualJwt
to call the TodoListService-ManualJwt
Running in Azure Web Sites
- In Visual Studio, go to the
TodoListClient-ManualJwt
project. - Open
TodoListClient\App.Config
. Only one change is needed - update thetodo:TodoListBaseAddress
key value to be the address of the website you published, for example, https://TodoListService-ManualJwt-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.
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.
In order to run this sample on Azure Government, you can follow through the steps above with a few variations:
-
Step 2:
- You must register this sample for your AAD Tenant in Azure Government by following Step 2 above in the Azure Government portal.
-
Step 3:
- Before configuring the sample, you must make sure your Visual Studio is connected to Azure Government.
- Navigate to the Web.config file. Replace the
ida:AADInstance
property in the Azure AD section withhttps://login.microsoftonline.us/
.
Once those changes have been accounted for, you should be able to run this sample on Azure Government.
If you are using this sample with an Azure AD B2C custom policy, you might want to read #22, and change step 3. in the About The Code paragraph.
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 opencode@microsoft.com with any additional questions or comments.
- Microsoft identity platform (Azure Active Directory for developers)
- MSAL.NET's conceptual documentation
- Quickstart: Register an application with the Microsoft identity platform
- Quickstart: Configure a client application to access web APIs
- Recommended pattern to acquire a token
- Token Cache serialization
For more information about token validation, see:
- Principles of Token validation
- Microsoft Identity Model Extension for .NET
- Protect a web API
- Verify scopes and roles in Web API
- TokenValidationParameters.cs
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.