Skip to content

Commit 5daeb1f

Browse files
committed
Improvements to Readme and configuration script
- Improving the Configure.ps1 script (by adding a comment explaining how to use it, fixing a bug, - slightly improving the structure of the Readme.md, moving to the modern voice,
1 parent ac8a043 commit 5daeb1f

File tree

2 files changed

+57
-22
lines changed

2 files changed

+57
-22
lines changed

AppCreationScripts/Configure.ps1

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,34 @@
1+
<#
2+
This script creates the Azure AD applications needed for this sample and updates the configuration files
3+
for the visual Studio projects from the data in the Azure AD applications.
4+
5+
Before running this script you need to install the AzureAD cmdlets as an administrator.
6+
For this:
7+
1) Run Powershell as an administrator
8+
2) in the PowerShell window, type: Install-Module AzureAD
9+
10+
There are three ways to run this script
11+
Option1 (interactive)
12+
---------------------
13+
Just run . .\Configue.ps1, and you will be prompted to sign-in (email address, password, and if needed MFA).
14+
The script will be run as the signed-in user and will use the tenant in which the user is defined.
15+
16+
Option 2 (Interactive, but create apps in a specified tenant)
17+
-------------------------------------------------------------
18+
If you want to create the apps in a specific tenant, before you run this script
19+
- In the Azure portal (https://portal.azure.com), choose your active directory tenant, then go to the Properties of the tenant and copy
20+
the DirectoryID. This is what we'll use in this script for the tenant ID
21+
- run . .\Configue.ps1 -TenantId [place here the GUID representing the tenant ID]
22+
23+
Option 2 (non-interactive)
24+
---------------------------
25+
This supposes that you know the credentials of the user under which identity you want to create
26+
the applications. Here is an example of script you'd want to run in a PowerShell Window
27+
$secpasswd = ConvertTo-SecureString "[Password here]" -AsPlainText -Force
28+
$mycreds = New-Object System.Management.Automation.PSCredential ("[login@tenantName here]", $secpasswd)
29+
. .\Configure.ps1 -Credential $mycreds
30+
#>
31+
132
# Adds the requiredAccesses (expressed as a pipe separated string) to the requiredAccess structure
233
# The exposed permissions are in the $exposedPermissions collection, and the type of permission (Scope | Role) is
334
# described in $permissionType
@@ -45,13 +76,14 @@ Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requ
4576
}
4677

4778
# $sp.AppRoles | Select Id,AdminConsentDisplayName,Value: To see the list of all the Application permissions for the application
48-
if ($requiredDelegatedPermissions)
79+
if ($requiredApplicationPermissions)
4980
{
5081
AddResourcePermission $requiredAccess -exposedPermissions $sp.AppRoles -requiredAccesses $requiredApplicationPermissions -permissionType "Role"
5182
}
5283
return $requiredAccess
5384
}
5485

86+
5587
# Replace the value of an appsettings of a given key in an XML App.Config file.
5688
Function ReplaceSetting([string] $configFilePath, [string] $key, [string] $newValue)
5789
{
@@ -69,6 +101,7 @@ Function ReplaceSetting([string] $configFilePath, [string] $key, [string] $newVa
69101
$content.save($configFilePath)
70102
}
71103

104+
72105
Function ConfigureApplications
73106
{
74107
<#.Description

README.md

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,36 +10,34 @@ endpoint: AAD V1
1010
![](https://identitydivision.visualstudio.com/_apis/public/build/definitions/a7934fdd-dcde-4492-a406-7fad6ac00e17/18/badge)
1111

1212
# Manually validating a JWT access token in a web API
13-
# Token Validation
14-
A token represent 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.
13+
## About this sample
14+
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](https://github.com/Azure-Samples/active-directory-dotnet-native-desktop) 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](https://github.com/Azure-Samples/active-directory-dotnet-native-desktop) sample.
15+
16+
## Scenario: protecting a Web API - acquiring a token for the protected Web API
17+
When you want to protect a Web API, you request your clients to get a [Security token](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-dev-glossary#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.
1518

16-
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.
19+
### Token Validation
20+
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.
1721

18-
# Validate the claims
22+
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.
23+
24+
### Validating the claims
1925
When an application receives an ID token upon user sign-in, it should also perform a few checks against the claims in the ID token. These include but are not limited to:
2026
- **audience** claim, to verify that the ID token was intended to be given to your application
2127
- **not before** and "expiration time" claims, to verify that the ID token has not expired
2228
- **issuer** claim, to verify that the token was issued to your app by the v2.0 endpoint
2329
- **nonce**, as a token replay attack mitigation
2430

25-
Though developers are advised to use standard library methods like [JwtSecurityTokenHandler.ValidateToken Method (JwtSecurityToken)](https://msdn.microsoft.com/en-us/library/dn451163(v=vs.114).aspx) to do most of the aforementioned heavy lifting. Developers can further extend the validation process by making decisions based on claims recieved in the token. For example, multi-tenant applications can extend the standard validation by inspecting value of the "tid" claim 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 is listed in the [Azure AD token reference](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims).
31+
You are advised to use standard library methods like [JwtSecurityTokenHandler.ValidateToken Method (JwtSecurityToken)](https://msdn.microsoft.com/en-us/library/dn451163(v=vs.114).aspx) to do most of the aforementioned heavy lifting. You can further extend the validation process by making decisions based on claims recieved 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 is listed in the [Azure AD token reference](https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-token-and-claims). 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](https://jwt.ms) tool.
2632

27-
## About this sample
28-
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](https://github.com/Azure-Samples/active-directory-dotnet-native-desktop) sample, except in the TodoListService instead of using OWIN middleware to process the token, the token is processed manually in application code. The client is unchanged from the [NativeClient-DotNet](https://github.com/Azure-Samples/active-directory-dotnet-native-desktop) sample.
29-
30-
The manual JWT validation occurs in the `TokenValidationHandler` implementation in the `Global.aspx.cs` file in the TodoListService-ManualJwt project.
3133
### More information
32-
3334
For more information about how the protocols work in this scenario and other scenarios, see [Authentication Scenarios for Azure AD](http://go.microsoft.com/fwlink/?LinkId=394414).
3435

3536
> Looking for previous versions of this code sample? Check out the tags on the [releases](../../releases) GitHub page.
3637
3738
## How To Run This Sample
3839

3940
>[!Note] If you want to run this sample on **Azure Government**, navigate to the "Azure Government Deviations" section at the bottom of this page.
40-
>
41-
>
42-
>
4341
4442
To run this sample you will need:
4543
- [Visual Studio 2017](https://aka.ms/vsdownload)
@@ -55,8 +53,8 @@ From your shell or command line:
5553

5654
### Step 2: Register the sample with your Azure Active Directory tenant
5755
There are two options:
58-
- Option 1: you run the `Configure.ps1` PowerShell script which creates two applications in the Azure Active Directory, (one for the client and one for the service), and then updates the configuration files in the Visual Studio projects to point to those two newly created apps.
59-
- Option 2: you do the same manually.
56+
- Option 1: you run the `Configure.ps1` PowerShell script which creates two applications in the Azure Active Directory, (one for the client and one for the service), and then updates the configuration files in the Visual Studio projects to point to those two newly created apps. Instructions for these option are provided in the [Configure.ps1](./AppCreationScripts/Configure.ps1) file
57+
- Option 2: you do the same manually through the Azure portal and modifying the code. This is what is explained below:
6058

6159
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant.
6260

@@ -102,7 +100,7 @@ There are two projects in this sample. Each needs to be separately registered i
102100

103101
### Step 4: Run the sample
104102

105-
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.
103+
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.
106104

107105
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.
108106

@@ -119,12 +117,15 @@ First, in Visual Studio 2017 create an empty solution to host the projects. The
119117
1. In Visual Studio , create a new `Visual C#` `ASP.NET Web Application (.NET Framework)`. Choose `Web Api` in the next screen. Leave the project's chosen authentication mode as the default, i.e. `No Authentication`".
120118
2. Set SSL Enabled to be True. Note the SSL URL.
121119
3. In the project properties, Web properties, set the Project Url to be the SSL URL.
122-
4. 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, as it requires .Net Framework 5.x.
120+
4. 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.
123121
5. Add an assembly reference to `System.IdentityModel`.
124122
6. In the `Models` folder add a new class called `TodoItem.cs`. Copy the implementation of TodoItem from this sample into the class.
125123
7. Add a new, empty, Web API 2 controller called `TodoListController`.
126124
8. Copy the implementation of the TodoListController from this sample into the controller.
127-
9. 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());`.
125+
9. 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()`,
126+
```C#
127+
GlobalConfiguration.Configuration.MessageHandlers.Add(new TokenValidationHandler());
128+
```
128129
10. In `web.config` create keys for `ida:AADInstance`, `ida:Tenant`, and `ida:Audience` and set them accordingly. For the public Azure cloud, the value of `ida:AADInstance` is `https://login.microsoftonline.com/{0}`.
129130

130131
### Creating the TodoListClient Project
@@ -149,11 +150,12 @@ In order to run this sample on Azure Government you can follow through the steps
149150
- Step 3:
150151
- Before configuring the sample, you must make sure your [Visual Studio is connected to Azure Government](https://docs.microsoft.com/azure/azure-government/documentation-government-get-started-connect-with-vs).
151152
- Navigate to the Web.config file. Replace the `ida:AADInstance` property in the Azure AD section with `https://login.microsoftonline.us/`.
152-
153153
Once those changes have been accounted for, you should be able to run this sample on Azure Government.
154154

155155
## More information
156-
For more information see ADAL.NET's conceptual documentation:
156+
For more information on how to acquire a token in the client application, see ADAL.NET's conceptual documentation:
157157
- [Recommanded pattern to acquire a token](https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/AcquireTokenSilentAsync-using-a-cached-token#recommended-pattern-to-acquire-a-token)
158+
159+
For more information about token validation, see:
158160
- [JwtSecurityTokenHandler.ValidateToken Method (JwtSecurityToken)](https://msdn.microsoft.com/en-us/library/dn451163(v=vs.114).aspx)
159-
- [Principles of Token Validation](http://www.cloudidentity.com/blog/2014/03/03/principles-of-token-validation/)
161+
- [Principles of Token Validation](http://www.cloudidentity.com/blog/2014/03/03/principles-of-token-validation/)

0 commit comments

Comments
 (0)