Skip to content

Commit 4dbe43c

Browse files
author
Kalyan Krishna
authored
Merge pull request #147 from Azure-Samples/kkrishna/updates2019
Updated the groups sample a bit and updated guidance when using the session token cache provider
2 parents 3a5aacb + db49225 commit 4dbe43c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+1608
-323
lines changed

Diff for: 2-WebApp-graph-user/2-2-TokenCache/AppCreationScripts/Cleanup.ps1

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ if ($null -eq (Get-Module -ListAvailable -Name "AzureAD")) {
99
Install-Module "AzureAD" -Scope CurrentUser
1010
}
1111
Import-Module AzureAD
12-
$ErrorActionPreference = 'Stop'
12+
$ErrorActionPreference = "Stop"
1313

1414
Function Cleanup
1515
{

Diff for: 2-WebApp-graph-user/2-2-TokenCache/AppCreationScripts/Configure.ps1

+8-5
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ Function AddResourcePermission($requiredAccess, `
6565
}
6666

6767
#
68-
# Exemple: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read"
68+
# Example: GetRequiredPermissions "Microsoft Graph" "Graph.Read|User.Read"
6969
# See also: http://stackoverflow.com/questions/42164581/how-to-configure-a-new-azure-ad-application-through-powershell
7070
Function GetRequiredPermissions([string] $applicationDisplayName, [string] $requiredDelegatedPermissions, [string]$requiredApplicationPermissions, $servicePrincipal)
7171
{
@@ -134,18 +134,18 @@ Function UpdateTextFile([string] $configFilePath, [System.Collections.HashTable]
134134
Set-Content -Path $configFilePath -Value $lines -Force
135135
}
136136

137-
138137
Set-Content -Value "<html><body><table>" -Path createdApps.html
139138
Add-Content -Value "<thead><tr><th>Application</th><th>AppId</th><th>Url in the Azure portal</th></tr></thead><tbody>" -Path createdApps.html
140139

140+
$ErrorActionPreference = "Stop"
141+
141142
Function ConfigureApplications
142143
{
143144
<#.Description
144145
This function creates the Azure AD applications for the sample in the provided Azure AD tenant and updates the
145146
configuration files in the client and service project of the visual studio solution (App.Config and Web.Config)
146147
so that they are consistent with the Applications parameters
147148
#>
148-
149149
$commonendpoint = "common"
150150

151151
# $tenantId is the Active Directory Tenant. This is a GUID which represents the "Directory ID" of the AzureAD tenant
@@ -177,7 +177,7 @@ Function ConfigureApplications
177177
$tenant = Get-AzureADTenantDetail
178178
$tenantName = ($tenant.VerifiedDomains | Where { $_._Default -eq $True }).Name
179179

180-
# Get the user running the script
180+
# Get the user running the script to add the user as the app owner
181181
$user = Get-AzureADUser -ObjectId $creds.Account.Id
182182

183183
# Create the webApp AAD application
@@ -187,6 +187,7 @@ Function ConfigureApplications
187187
$fromDate = [DateTime]::Now;
188188
$key = CreateAppKey -fromDate $fromDate -durationInYears 2 -pw $pw
189189
$webAppAppKey = $pw
190+
# create the application
190191
$webAppAadApplication = New-AzureADApplication -DisplayName "WebApp-OpenIDConnect-DotNet-code-v2" `
191192
-HomePage "https://localhost:44321/" `
192193
-LogoutUrl "https://localhost:44321/signout-oidc" `
@@ -197,6 +198,7 @@ Function ConfigureApplications
197198
-Oauth2AllowImplicitFlow $true `
198199
-PublicClient $False
199200

201+
# create the service principal of the newly created application
200202
$currentAppId = $webAppAadApplication.AppId
201203
$webAppServicePrincipal = New-AzureADServicePrincipal -AppId $currentAppId -Tags {WindowsAzureActiveDirectoryIntegratedApp}
202204

@@ -241,7 +243,8 @@ Function ConfigureApplications
241243
# Pre-requisites
242244
if ((Get-Module -ListAvailable -Name "AzureAD") -eq $null) {
243245
Install-Module "AzureAD" -Scope CurrentUser
244-
}
246+
}
247+
245248
Import-Module AzureAD
246249

247250
# Run interactively (will ask you for the tenant ID)

Diff for: 2-WebApp-graph-user/2-2-TokenCache/AppCreationScripts/sample.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"Sample": {
3-
"Title": "Using the Microsoft identity platform to call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, on behalf of a user signing-in using their work and school or Microsoft personal account",
3+
"Title": "Call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, using Sql Server for caching tokens",
44
"Level": 200,
55
"Client": "ASP.NET Core 2.x Web App",
66
"Service": "Microsoft Graph",
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
services: active-directory
3+
platforms: dotnet
4+
author: kalyankrishna1
5+
level: 200
6+
client: ASP.NET Core 2.x Web App
7+
service: Microsoft Graph
8+
endpoint: Microsoft identity platform
9+
---
10+
11+
# Call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, using Sql Server for caching tokens
12+
13+
## About this sample
14+
15+
[![Build status](https://identitydivision.visualstudio.com/IDDP/_apis/build/status/AAD%20Samples/.NET%20client%20samples/ASP.NET%20Core%20Web%20App%20tutorial)](https://identitydivision.visualstudio.com/IDDP/_build/latest?definitionId=819)
16+
17+
## Scenario
18+
19+
Starting from a .NET Core 2.2 MVC Web app that uses OpenID Connect to sign in users, this chapter of the tutorial shows how to make a call to Microsoft Graph `/me` endpoint on behalf of the signed-in user. This sample additionally provides instructions on how to use Sql Server for caching tokens.
20+
21+
It leverages the ASP.NET Core OpenID Connect middleware and Microsoft Authentication Library for .NET (MSAL.NET). The complexities of the library's integration with the ASP.NET Core dependency Injection patterns is encapsultated into the `Microsoft.Identity.Web` library project, which is a part of this tutorial.
22+
23+
![Sign in with the Microsoft identity platform](ReadmeFiles/sign-in.png)
24+
25+
## How to run this sample
26+
27+
To run this sample, you'll need:
28+
29+
- [Visual Studio 2017](https://aka.ms/vsdownload) or just the [.NET Core SDK](https://www.microsoft.com/net/learn/get-started)
30+
- An Internet connection
31+
- A Windows machine (necessary if you want to run the app on Windows)
32+
- An OS X machine (necessary if you want to run the app on Mac)
33+
- A Linux machine (necessary if you want to run the app on Linux)
34+
- 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](https://azure.microsoft.com/en-us/documentation/articles/active-directory-howto-tenant/)
35+
- 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](https://portal.azure.com) with a Microsoft account and have never created a user account in your directory before, you need to do that now.
36+
37+
### Step 1: Clone or download this repository
38+
39+
From your shell or command line:
40+
41+
```Shell
42+
git clone https://github.com/Azure-Samples/microsoft-identity-platform-aspnetcore-webapp-tutorial webapp
43+
cd webapp
44+
```
45+
> 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.
46+
47+
Go to the `"2-WebApp-graph-user\2-2-TokenCache"` folder
48+
49+
```Sh
50+
cd "2-WebApp-graph-user\2-2-TokenCache"
51+
```
52+
53+
#### In the appsettings.json file, configure a Sql server database for token caching, if you have not already done so:
54+
55+
1. In the `TokenCacheDbConnStr` key, provide the Sql server connection string to the database you wish to use for token caching.
56+
> Note:
57+
> If you want to test this sample locally with Visual Studio, you might want to use localdb, which is installed with Visual Studio.
58+
> In that case, use the following connection string:
59+
>
60+
> ```XML
61+
> "ConnectionStrings": {
62+
> "TokenCacheDbConnStr": "Data Source=(LocalDb)\\MSSQLLocalDB;Database=MY_TOKEN_CACHE_DATABASE;Trusted_Connection=True;"
63+
> },
64+
> ```
65+
66+
1. If you do not have an existing database and tables needed for token caching, this sample can use [EF Core- code first](https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/new-db?tabs=visual-studio) to create a database and tables for you. to do that, follow the steps below.
67+
1. In the file `Startup.cs`, uncomment the code under the **// Uncomment the following to initialize the sql server database with tables required to cache tokens.**. This comment exists once in the **ConfigureServices** methods.
68+
1. Run the solution again, when a user signs-in the very first time, the Entity Framework will create the database and tables `AppTokenCache` and `UserTokenCache` for app and user token caching respectively.
69+
70+
- In case you want to deploy your app in Sovereign or national clouds, ensure the `GraphApiUrl` option matches the one you want. By default this is Microsoft Graph in the Azure public cloud
71+
72+
```JSon
73+
"GraphApiUrl": "https://graph.microsoft.com"
74+
```
75+
76+
77+
### Step 3: Run the sample
78+
79+
1. Clean the solution, rebuild the solution, and run it.
80+
81+
2. Open your web browser and make a request to the app. The app immediately attempts to authenticate you via the Microsoft identity platform endpoint. Sign in with your personal account or with a work or school account.
82+
83+
3. Go to the **Profile** page, you should now see all kind of information about yourself as well as your picture (a call was made to the Microsoft Graph */me* endpoint)
84+
85+
> 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](../../../../issues) page.
86+
87+
## About the code
88+
89+
Starting from the [previous phase of the tutorial](../../2-WebApp-graph-user/2-1-Call-MSGraph), the code was incrementally updated with the following steps:
90+
91+
### Update the `Startup.cs` file to enable Token caching using Sql database.
92+
93+
```CSharp
94+
public void ConfigureServices(IServiceCollection services)
95+
{
96+
. . .
97+
// Token acquisition service based on MSAL.NET
98+
// and the Sql server based token cache implementation
99+
services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
100+
.AddMsal(new string[] { Constants.ScopeUserRead })
101+
.AddSqlAppTokenCache(Configuration)
102+
.AddSqlPerUserTokenCache(Configuration);
103+
```
104+
105+
The aforementioned four lines of code are explained below.
106+
107+
1. The first two lines enable MSAL.NET to hook-up to the OpenID Connect events to redeem the authorization code obtained by the ASP.NET Core middleware. After obtaining a token for Microsoft Graph, it saves it into the token cache, for use by the Controllers.
108+
1. The last two lines hook up the Sql server database based token caching solution to MSAL.NET. The Sql based token cache requires a **Connection string** named `TokenCacheDbConnStr` available in the **ConnectionStrings** collections of the **appsettings.json** configuration file.
109+
110+
The files `MSALAppSqlTokenCacheProvider.cs` and `MSALPerUserSqlTokenCacheProvider` of the `Microsoft.Identity.Web` project contains the app and per-user token cache implementations that use Sql server as the token cache.
111+
112+
### Sharing the same Token Cache database between apps
113+
114+
Since we are using `IDataProtector` to protect the token being persisted on the database, in order to enable it to be used between different apps, `SetApplicationName()` must be configured with the same value for all apps. You can read [more details about IDataProtector here.](https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-2.2#setapplicationname)
115+
116+
```csharp
117+
services.AddDataProtection()
118+
.SetApplicationName("WebApp_Tutorial");
119+
```
120+
121+
## Next steps
122+
123+
- Learn how to enable distributed caches in [token cache serialization](../2.2.%20token%20cache%20serialization)
124+
- Learn how the same principle you've just learnt can be used to call:
125+
- [several Microsoft APIs](../../3-WebApp-multi-APIs), which will enable you to learn how incremental consent and conditional access is managed in your Web App
126+
- 3rd party, or even [your own Web API](../../4-WebApp-your-API), which will enable you to learn about custom scopes
127+
128+
## Learn more
129+
130+
- Learn how [Microsoft.Identity.Web](../../Microsoft.Identity.Web) works, in particular hooks-up to the ASP.NET Core ODIC events
131+
- [Use HttpClientFactory to implement resilient HTTP requests](https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests) used by the Graph custom service

0 commit comments

Comments
 (0)