Skip to content

Commit 41c8551

Browse files
committed
Adapting the README.md to V2
1 parent d2ca81e commit 41c8551

File tree

1 file changed

+80
-42
lines changed

1 file changed

+80
-42
lines changed

README.md

Lines changed: 80 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,63 +2,89 @@
22
services: active-directory
33
platforms: dotnet
44
author: jmprieur
5+
level: 200
6+
service: ASP.NET Core Web App
7+
endpoint: AAD V2
58
---
9+
# Integrating Azure AD V2 into an ASP.NET Core web app
610

7-
# Integrating Azure AD into an ASP.NET Core web app
8-
9-
This sample shows how to build a .NET MVC web app that uses OpenID Connect to sign-in users from a single Azure Active Directory (Azure AD) tenant using the ASP.NET Core OpenID Connect middleware.
11+
This sample shows how to build a .NET Core MVC Web app that uses OpenID Connect to sign in users with their Work and School or Microsoft personal account (formerly live accounts). It leverages the ASP.NET Core OpenID Connect middleware.
1012

1113
For more information on how the protocols work in this scenario and other scenarios, see [Authentication Scenarios for Azure AD](http://go.microsoft.com/fwlink/?LinkId=394414).
1214

1315
## How to run this sample
1416

15-
If you are interested in ASP.NET Core 1.1, please look at branch [aspnet_core_1_1](https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/tree/aspnet_core_1_1).
16-
1717
To run this sample:
18-
- Install .NET Core for Windows by following the instructions at [.NET and C# - Get Started in 10 Minutes](https://www.microsoft.com/net/core). In addition to developing on Windows, you can develop on [Linux](https://www.microsoft.com/net/core#linuxredhat), [Mac](https://www.microsoft.com/net/core#macos), or [Docker](https://www.microsoft.com/net/core#dockercmd).
18+
19+
- Install .NET Core (for example for Windows) by following the instructions at [.NET and C# - Get Started in 10 Minutes](https://www.microsoft.com/net/core). In addition to developing on Windows, you can develop on [Linux](https://www.microsoft.com/net/core#linuxredhat), [Mac](https://www.microsoft.com/net/core#macos), or [Docker](https://www.microsoft.com/net/core#dockercmd).
1920
- An Azure AD tenant. For more information on how to obtain an Azure AD tenant, see [How to get an Azure AD tenant](https://azure.microsoft.com/documentation/articles/active-directory-howto-tenant/).
2021

2122
### Step 1: Register the sample with your Azure AD tenant
2223

23-
1. Sign in to the [Azure portal](https://portal.azure.com).
24-
25-
2. On the top bar, select your account. Under the **DIRECTORY** list, choose the Active Directory tenant where you wish to register your app. If there isn't a **DIRECTORY** list in the drop down menu, skip this step, as you only have a single tenant associated with your Azure account. For more information, see [How to get an Azure Active Directory tenant](https://docs.microsoft.com/azure/active-directory/develop/active-directory-howto-tenant).
26-
27-
3. In the left navigation sidebar, select **Azure Active Directory**. If you don't see **Azure Active Directory** in the list, select **More Services** and choose **Azure Active Directory** in the **SECURITY + IDENTITY** section of the service list.
28-
29-
4. From the sidebar, select **App registrations**.
30-
31-
5. Select **New application registration** and provide a friendly name for the app, app type, and sign-on URL:
32-
**Name**: **WebApp-OpenIDConnect-DotNet**
33-
**Application Type**: **Web app / API**
34-
**Sign-on URL**: `http://localhost:5000/signin-oidc`
35-
Select **Create** to register the app.
36-
37-
6. On the **Properties** blade, set the **Logout URL** to `http://localhost:5000/signout-oidc` and select **Save**.
38-
39-
7. From the Azure portal, note the following information:
40-
41-
**The Tenant domain:** See the **App ID URI** base URL. For example: `contoso.onmicrosoft.com`
42-
43-
**The Tenant ID:** See the **Endpoints** blade. Record the GUID from any of the endpoint URLs. For example: `da41245a5-11b3-996c-00a8-4d99re19f292`
44-
45-
**The Application ID (Client ID):** See the **Properties** blade. For example: `ba74781c2-53c2-442a-97c2-3d60re42f403`
24+
1. Sign in to the [Application registration portal](https://apps.dev.microsoft.com) either a personal or work or school Microsoft account
25+
1. Look at your list of Microsoft apps
26+
1. Click **Add an app**, and give it a name. Then press **Create**. The portal will assign your app a globally unique Application ID that you'll use later in your code.
27+
1. Click on **Add Platform**, and in the dialog press the **Web** icon.
28+
1. In the Redirect URLs field, add `http://localhost:5000/` and `http://localhost:5000/signin-oidc`
4629

4730
> [!NOTE]
4831
> The base address in the **Sign-on URL** and **Logout URL** settings is `http://localhost:5000`. This localhost address allows the sample app to run insecurely from your local system. Port 5000 is the default port for the [Kestrel server](https://docs.microsoft.com/aspnet/core/fundamentals/servers/kestrel). Update these URLs if you configure the app for production use (for example, `https://www.contoso.com/signin-oidc` and `https://www.contoso.com/signout-oidc`).
4932
5033
### Step 2: Create the sample
5134

52-
This sample was created from the 2.0 [dotnet new mvc](https://docs.microsoft.com/dotnet/core/tools/dotnet-new?tabs=netcore2x) template with `SingleOrg` authentication. You can create the sample from the command line or clone/download this repository:
35+
This sample was created from the dotnet core 2.0 template [dotnet new mvc](https://docs.microsoft.com/dotnet/core/tools/dotnet-new?tabs=netcore2x) template with `SingleOrg` authentication, and then tweaked to let it support tokens for the Azure AD V2 endpoint. You can create the sample from the command line or clone/download this repository:
36+
37+
#### To create the sample from the command line
5338

54-
- To create the sample from the command line, execute the following command:
39+
- Execute the following command:
5540

5641
```console
57-
dotnet new mvc --auth SingleOrg --client-id <CLIENT_ID_(APP_ID)> --tenant-id <TENANT_ID> --domain <TENANT_DOMAIN>
42+
dotnet new mvc --auth SingleOrg --client-id <CLIENT_ID_(APP_ID)>
5843
```
59-
Use the values that you recorded from the Azure portal for \<CLIENT\_ID\_(APP\_ID)>, \<TENANT\_ID>, and \<TENANT\_DOMAIN>.
6044

61-
- To clone/download this sample, execute the following command from your shell or command line:
45+
Use the value that you recorded from the Azure portal for \<CLIENT\_ID\_(APP\_ID)>.
46+
47+
- Then:
48+
49+
- Modify the `Configure` method in `Extensions\AzureAdAuthenticationBuilderExtensions.cs` file. This method show be as follows (the changed lines are the lines containing `Authority`, and `ValidateIssuer`)
50+
51+
```CSharp
52+
public void Configure(string name, OpenIdConnectOptions options)
53+
{
54+
options.ClientId = _azureOptions.ClientId;
55+
options.Authority = $"{_azureOptions.Instance}common/v2.0"; // V2 specific
56+
options.UseTokenLifetime = true;
57+
options.RequireHttpsMetadata = false;
58+
options.TokenValidationParameters.ValidateIssuer = false; // accept any tenant
59+
}
60+
```
61+
- Modify `Views\Shared\_LoginPartial.cshtml` to have the following content:
62+
63+
```CSharp
64+
@using System.Security.Claims
65+
66+
@if (User.Identity.IsAuthenticated)
67+
{
68+
var identity = User.Identity as ClaimsIdentity; // V2 specific
69+
string preferred_username = identity.Claims.FirstOrDefault(c => c.Type == "preferred_username")?.Value;
70+
<ul class="nav navbar-nav navbar-right">
71+
<li class="navbar-text">Hello @preferred_username</li>
72+
<li><a asp-area="" asp-controller="Account" asp-action="SignOut">Sign out</a></li>
73+
</ul>
74+
}
75+
else
76+
{
77+
<ul class="nav navbar-nav navbar-right">
78+
<li><a asp-area="" asp-controller="Account" asp-action="Signin">Sign in</a></li>
79+
</ul>
80+
}
81+
```
82+
83+
This change is needed because the claims are different in the Azure AD V1 and Azure AD V2 tokens. Here the 'preferred_username' claim is used, which turns out to be the user's email address.
84+
85+
#### To clone / download the sample
86+
87+
- Execute the following command from your shell or command line:
6288

6389
```console
6490
git clone https://github.com/Azure-Samples/active-directory-dotnet-webapp-openidconnect-aspnetcore.git
@@ -70,30 +96,42 @@ This sample was created from the 2.0 [dotnet new mvc](https://docs.microsoft.com
7096

7197
Build the solution and run it.
7298

73-
Make a request to the app. The app immediately attempts to authenticate you via Azure AD. Sign in with the username and password of a user account that is in your Azure AD tenant. You can also use your tenant's Global Administrator account. If you wish to create a user in the tenant, select **Add a user** from the **Quick tasks** panel. The **Quick tasks** panel is found on the Azure AD tenant's blade in the portal.
99+
Make a request to the app. The app immediately attempts to authenticate you via Azure AD. Sign in with the username and password of a user account that is in your Azure AD tenant or your microsoft personal account.
74100

75101
## About The code
76102

77-
This sample shows how to use the OpenID Connect ASP.NET Core middleware to sign-in users from a single Azure AD tenant. The middleware is initialized in the `Startup.cs` file by passing it the Client ID of the app and the URL of the Azure AD tenant where the app is registered, which is read from the `appsettings.json` file. The middleware takes care of:
103+
This sample shows how to use the OpenID Connect ASP.NET Core middleware to sign in users from a single Azure AD tenant. The middleware is initialized in the `Startup.cs` file by passing it the Client ID of the app and the URL of the Azure AD tenant where the app is registered, which is read from the `appsettings.json` file. The middleware takes care of:
104+
78105
- Downloading the Azure AD metadata, finding the signing keys, and finding the issuer name for the tenant.
79106
- Processing OpenID Connect sign-in responses by validating the signature and issuer in an incoming JWT, extracting the user's claims, and putting the claims in `ClaimsPrincipal.Current`.
80-
- Integrating with the session cookie ASP.NET Core middleware to establish a session for the user.
107+
- Integrating with the session cookie ASP.NET Core middleware to establish a session for the user.
81108

82109
You can trigger the middleware to send an OpenID Connect sign-in request by decorating a class or method with the `[Authorize]` attribute or by issuing a challenge (see the `AccountController.cs` file):
83110

84111
```csharp
85112
return Challenge(
86-
new AuthenticationProperties { RedirectUri = redirectUrl },
113+
new AuthenticationProperties { RedirectUri = redirectUrl },
87114
OpenIdConnectDefaults.AuthenticationScheme);
88115
```
89116

90-
Similarly, you can send a signout request:
117+
Similarly, you can send a sign-out request:
91118

92119
```csharp
93120
return SignOut(
94-
new AuthenticationProperties { RedirectUri = callbackUrl },
95-
CookieAuthenticationDefaults.AuthenticationScheme,
121+
new AuthenticationProperties { RedirectUri = callbackUrl },
122+
CookieAuthenticationDefaults.AuthenticationScheme,
96123
OpenIdConnectDefaults.AuthenticationScheme);
97124
```
98125

99-
The middleware in this project is created as a part of the open source [ASP.NET Security](https://github.com/aspnet/Security) project.
126+
The specific Azure AD V2 code is in `Configure(string name, OpenIdConnectOptions options)`:
127+
128+
```CSharp
129+
options.Authority = $"{_azureOptions.Instance}common/v2.0"; // V2 specific
130+
options.TokenValidationParameters.ValidateIssuer = false; // accept any tenant
131+
```
132+
133+
The first line tells the middleware to let sign-in users with the Azure AD V2 endpoint, that is with their work and school account or Microsoft personal account.
134+
135+
The second line tells the middleware to not validate the tenants. If you want to validate the tenants, you can set `ValidateIssuer` to true, and add a delegate as the `options.TokenValidationParameters.IssuerValidator` property.
136+
137+
The middleware in this project is created as a part of the open-source [ASP.NET Security](https://github.com/aspnet/Security) project.

0 commit comments

Comments
 (0)