services | platforms | author | level | client | service | endpoint |
---|---|---|---|---|---|---|
active-directory |
dotnet |
jmprieur |
300 |
.NET Desktop (WPF) |
ASP.NET MVC Web API |
AAD V1 |
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 4.5. 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 developineg, 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 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 value of the tid
claim (Tenant ID) against a set of pre-selected tenants to ensure they only honor token 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.
To run this sample, you'll need:
- 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. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, if you signed in to the Azure portal with a Microsoft account and have never created a user account in your directory before, you need to do that now.
From your shell or command line:
git clone https://github.com/Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation.git
Given that the name of the sample is pretty long, and so are the name of the referenced NuGet pacakges, 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 in the paragraphs below (Step 2 and Step 3)
- or use PowerShell scripts that:
- automatically create for you the Azure AD applications and related objects (passwords, permissions, dependencies)
- modify the Visual Studio projects' configuration files.
If you want to use this automation, read the instructions in App Creation Scripts
As a first step you'll need to:
- Sign in to the Azure portal.
- On the top bar, click on your account, and then on Switch Directory.
- Once the Directory + subscription pane opens, choose the Active Directory tenant where you wish to register your application, from the Favorites or All Directories list.
- Click on All services in the left-hand nav, and choose Azure Active Directory.
In the next steps, you might need the tenant name (or directory name) or the tenant ID (or directory ID). These are presented in the Properties of the Azure Active Directory window respectively as Name and Directory ID
- In the Azure Active Directory pane, click on App registrations and choose New application registration.
- Enter a friendly name for the application, for example 'TodoListService-ManualJwt' and select 'Web app / API' as the Application Type.
- For the sign-on URL, enter the base URL for the sample, which is by default
https://localhost:44324
. - Click on Create to create the application.
- In the succeeding page, Find the Application ID value and copy it to the clipboard. You'll need it to configure the Visual Studio configuration file for this project.
- Then click on Settings, and choose Properties.
- For the App ID URI, replace the guid in the generated URI 'https://<your_tenant_name>/<guid>', with the name of your service, for example, 'https://<your_tenant_name>/TodoListService-ManualJwt' (replacing
<your_tenant_name>
with the name of your Azure AD tenant)
- Click on App registrations and choose New application registration.
- Enter a friendly name for the application, for example 'TodoListClient-ManualJwt' and select 'Native' as the Application Type. For the redirect URI, enter
https://TodoListClient
. Please note that the Redirect URI will not be used in this sample, but it needs to be defined nonetheless. Click on Create to create the application. - In the succeeding page, Find the Application ID value and copy it to the clipboard.
- Then click on Settings and choose Properties.
- Configure Permissions for your application - in the Settings menu, choose the Required permissions section, click on Add, then Select an API, and type 'TodoListService' in the textbox and hit enter. Select 'TodoListService-ManualJwt' from the results and click the 'Select' button. Then, click on Select Permissions and select 'Access TodoListService-ManualJwt'. Click the 'Select' button again to close this screen. Click on Done to finish adding the permission.
In the steps below, ClientID is the same as Application ID or AppId.
Open the solution in Visual Studio to configure the projects
- Open the
TodoListService-ManualJwt\Web.Config
file - Find the app key
ida:Tenant
and replace the existing value with your AAD tenant name. - Find the app key
ida:Audience
and replace the existing value with the App ID URI you registered earlier for the TodoListService-ManualJwt app. For instance usehttps://<your_tenant_name>/TodoListService-ManualJwt
, where<your_tenant_name>
is the name of your Azure AD tenant. - Find the app key
ida:ClientId
and replace the existing value with the application ID (clientId) of theTodoListService-ManualJwt
application copied from the Azure portal.
- Open the
TodoListClient\App.Config
file - Find the app key
ida:Tenant
and replace the existing value with your AAD tenant name. - Find the app key
ida:ClientId
and replace the existing value with the application ID (clientId) of theTodoListClient-ManualJwt
application copied from the Azure portal. - Find the app key
ida:RedirectUri
and replace the existing value with the Redirect URI for TodoListClient-ManualJwt app. For instance usehttps://<your_tenant_name>/TodoListClient-ManualJwt
, where<your_tenant_name>
is the name of your Azure AD tenant. - Find the app key
todo:TodoListResourceId
and replace the existing value with the App ID URI you registered earlier for the TodoListService-ManualJwt app. For instance usehttps://<your_tenant_name>/TodoListService-ManualJwt
, where<your_tenant_name>
is the name of your Azure AD tenant. - Find the app key
todo:TodoListBaseAddress
and replace the existing value with the base address of the TodoListService-ManualJwt project (by defaulthttps://localhost:44324
).
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 ADAL, and remembers the tokens from the previous run.
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 done on a controller method holding the [Authorize]
attribute, the TokenValidationHandler.SendAsync() method is called:
This method:
- gets the token from the Authorization headers
- verifies that the token has not expired
- gets the open ID configuration from the Azure AD discovery endpoint
- Sets the parameters to validate:
- 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 it delegates to the
JwtSecurityTokenHandler
class (provided by theSystem.IdentityModel.Tokens
library)
the TokenValidationHandler
class is registered with ASP.NET in the TodoListService-ManualJwt/Global.asx.cs
file, in the application_start() method:
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 4.5 NuGet, System.IdentityModel.Tokens.Jwt, version 4.x to the project. Note: Version 5.x will not work with this sample.
- Add an assembly reference to
System.IdentityModel
. - In the
Models
folder, add a new class calledTodoItem.cs
. Copy the implementation of TodoItem from this sample into the class. - Add a new, empty, Web API 2 controller called
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 Active Directory Authentication Library (ADAL) NuGet,
Microsoft.IdentityModel.Clients.ActiveDirectory
to the project. - Add assembly references to
System.Net.Http
,System.Web.Extensions
, andSystem.Configuration
. - Add a new class to the project called
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 called
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
,ida:RedirectUri
,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 + Mobile --> Web App, select the hosting plan and region, and give your web site a name, for example,
TodoListService-ManualJwt-contoso.azurewebsites.net
. Click Create Web Site. - Once the web site is created, click on it to manage it. For this set of steps, download the publish profile by clicking Get publish profile and save it. Other deployment mechanisms, such as from source control, can also be used.
- Switch to Visual Studio and go to the TodoListService 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 Settings and in the
Connection tab
, update the Destination URL so that it is https, 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 to the Azure portal.
- On the top bar, click on your account and under the Directory list, choose the Active Directory tenant containing the
TodoListService-ManualJwt
application. - On the applications tab, select the
TodoListService-ManualJwt
application. - From the Settings -> Reply URLs menu, update the Sign-On URL, and Reply URL fields to the address of your service, for example https://TodoListService-ManualJwt-contoso.azurewebsites.net. Save the configuration.
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.
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 [adal
dotnet
].
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 on how to acquire a token in the client application, see ADAL.NET's conceptual documentation:
For more information about token validation, see:
For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.