Skip to content

Commit ba0bb59

Browse files
committed
Updated README with instructions for Redis.
1 parent e89e7ae commit ba0bb59

File tree

3 files changed

+50
-19
lines changed

3 files changed

+50
-19
lines changed

2-WebApp-graph-user/2-2-TokenCache/README.md

Lines changed: 46 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ service: Microsoft Graph
88
endpoint: Microsoft identity platform
99
---
1010

11-
# Call the Microsoft Graph API from an An ASP.NET Core Web App, using Sql Server for caching tokens
11+
# Call the Microsoft Graph API from an An ASP.NET Core Web App, using Sql Server or Redis for caching tokens
1212

1313
## About this sample
1414

1515
[![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)
1616

1717
## Scenario
1818

19-
Starting from a .NET Core 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.
19+
Starting from a .NET Core 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 or Redis for caching tokens.
2020

2121
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 encapsulated into the `Microsoft.Identity.Web` library project, which is a part of this tutorial.
2222

@@ -135,16 +135,17 @@ Note: if you had used the automation to setup your application mentioned in [Ste
135135
1. Find the app key `Domain` and replace the existing value with your Azure AD tenant name.
136136
1. Find the app key `ClientSecret` and replace the existing value with the key you saved during the creation of the `WebApp-OpenIDConnect-DotNet-code-v2` app, in the Azure portal.
137137

138-
#### In the appsettings.json file, configure a Sql server database for token caching, if you have not already done so:
138+
#### In the appsettings.json file, configure a Sql server database for token caching:
139139

140140
1. In the `TokenCacheDbConnStr` key, provide the Sql server connection string to the database you wish to use for token caching.
141141
> Note:
142142
> If you want to test this sample locally with Visual Studio, you might want to use localdb, which is installed with Visual Studio.
143143
> In that case, use the following connection string:
144144
>
145145
> ```XML
146-
> "ConnectionStrings": {
146+
> "ConnectionStrings": {
147147
> "TokenCacheDbConnStr": "Data Source=(LocalDb)\\MSSQLLocalDB;Database=MY_TOKEN_CACHE_DATABASE;Trusted_Connection=True;"
148+
> // Rest of strings...
148149
> },
149150
> ```
150151
@@ -155,6 +156,18 @@ Note: if you had used the automation to setup your application mentioned in [Ste
155156
dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MY_TOKEN_CACHE_DATABASE;Integrated Security=True;" dbo TokenCache
156157
```
157158
159+
#### [OPTIONAL] In the appsettings.json file, configure a Redis instance for token caching:
160+
161+
1. In the `TokenCacheRedisConnStr` key, provide the Redis domain for your instance or `localhost` if testing on a local Redis database. Replace the value of the `TokenCacheRedisInstaceName` key with the name of your instance.
162+
> Note:
163+
> ```XML
164+
>"ConnectionStrings": {
165+
> // Rest of strings...
166+
> "TokenCacheRedisConnStr": "[Replace with your domain like so: <your-domain>.redis.cache.windows.net:6380,password=SomeLongPassword,ssl=True,abortConnect=False or with 'localhost' if running locally]",
167+
> "TokenCacheRedisInstaceName": "[Replace with your instance name]"
168+
> },
169+
> ```
170+
158171
- 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
159172
160173
```JSon
@@ -179,9 +192,9 @@ Starting from the [previous phase of the tutorial](../../2-WebApp-graph-user/2-1
179192

180193
### Reference Microsoft.Extensions.Caching.SqlServer
181194

182-
This sample proposes a distributed SQL token cache. To use it, you'll need to add a reference to the `Microsoft.Extensions.Caching.SqlServer` NuGet package
195+
This sample can use a distributed SQL token cache. To use it, you'll need to add a reference to the `Microsoft.Extensions.Caching.SqlServer` NuGet package
183196

184-
### Update the `Startup.cs` file to enable Token caching using Sql database.
197+
### Update the `Startup.cs` file to enable Token caching using Sql database
185198

186199
```CSharp
187200
public void ConfigureServices(IServiceCollection services)
@@ -207,17 +220,31 @@ public void ConfigureServices(IServiceCollection services)
207220
});
208221
```
209222

210-
The aforementioned lines of code are explained below.
211-
212223
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.
213224
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.
214225

215-
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.
226+
### Reference Microsoft.Extensions.Caching.StackExchangeRedis
227+
228+
This sample also has an optional distributed Redis token cache. To use it, you'll need to add a reference to the `Microsoft.Extensions.Caching.StackExchangeRedis` NuGet package
229+
230+
### Update the `Startup.cs` file to enable Token caching using Redis
231+
232+
```CSharp
233+
// Uncomment for Redis configuration. Be sure you DO NOT ADD BOTH an SQL cache and Redis cache
234+
services.AddStackExchangeRedisCache(options =>
235+
{
236+
options.Configuration = Configuration.GetConnectionString("TokenCacheRedisConnStr");
237+
options.InstanceName = Configuration.GetConnectionString("TokenCacheRedisInstanceName");
238+
});
239+
```
240+
241+
1. The code above hooks up the Redis database based token caching solution to MSAL.NET. The Redis based token cache requires a **Connection string** named `TokenCacheRedisConnStr` to connect to the Redis database and a **Connection string** named `TokenCacheRedisInstanceName` to name the instance tokens are stored to available in the **ConnectionStrings** collections of the **appsettings.json** configuration file.
216242

217243
## Next steps
218244

219245
- Learn how to enable distributed caches in [token cache serialization](../2.2.%20token%20cache%20serialization)
220246
- Learn more about the [Distributed SQL Server Cache](https://docs.microsoft.com/aspnet/core/performance/caching/distributed#distributed-sql-server-cache)
247+
- Learn more about the [Distributed Redis Cache](https://learn.microsoft.com/azure/azure-cache-for-redis/cache-overview)
221248
- Learn how the same principle you've just learnt can be used to call:
222249
- [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
223250
- 3rd party, or even [your own Web API](../../4-WebApp-your-API), which will enable you to learn about custom scopes
@@ -227,7 +254,6 @@ The files `MSALAppSqlTokenCacheProvider.cs` and `MSALPerUserSqlTokenCacheProvide
227254
- Learn how [Microsoft.Identity.Web](../../Microsoft.Identity.Web) works, in particular hooks-up to the ASP.NET Core OIDC events
228255
- [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
229256
230-
231257
## How to deploy this sample to Azure
232258

233259
This project has one WebApp project. To deploy it to the Azure Web Site, you'll need to:
@@ -243,15 +269,20 @@ This project has one WebApp project. To deploy it to the Azure Web Site, you'll
243269
1. Thereafter select the `Subscription`, `Resource Group`, `App service plan and Location`. `OS` will be **Windows** and `Publish` will be **Code**.
244270
1. Click `Create` and wait for the App Service to be created.
245271
1. Once you get the `Deployment succeeded` notification, then click on `Go to resource` to navigate to the newly created App service.
246-
1. The following steps provide instructions to create a Sql database that the sample needs. If you already have a Sql Server and database present and a connection string available, skip the steps till we ask you to provide the connections string in the `Application Settings`.
247-
1. Click `Create a resource` in the top left-hand corner again, select **Databases** --> **SQL Database**, to create a new database. Follow the `Quickstart tutorial` if needed.
272+
1. The following steps provide instructions to create a Sql database. Steps for setting up a Redis database are further down. If you already have a Redis or Sql Server and database present and a connection string available, skip the steps till we ask you to provide the connections string in the `Application Settings`.
273+
1. Click `Create a resource` in the top left-hand corner.
274+
1. If you want to setup an SQL database, select **Databases** --> **SQL Database**, to create a new database. Follow the `Quickstart tutorial` if needed.
248275
1. You can name the Sql server and database whatever you want to.
249276
1. Select or create a database server, and enter server login credentials. Carefully note down the username and password for the Sql server as you'll need it when constructing your Sql conenction string later.
250277
1. Wait for the `Deployment succeeded` notification, then click on `Go to resource` to navigate to the newly created database's manage screen.
251-
1. Click on **Connection Strings** on left menu and copy the **ADO.NET (SQL authentication)** connection string. Populate **User ID={your_username};Password={your_password};** with values your provided during database creation.Copy this connection string.
252-
1. Once the web site is created, locate it it in the **Dashboard** and click it to open **App Services** **Overview** screen.
253-
1. Click on **Application settings** in the left menu of the App service and add the copied Sql connection string in the **Connection strings** section as `DefaultConnection`.
278+
1. Click on **Application settings** in the left menu of the App service and add the copied Sql connection string in the **Connection strings** section as `DefaultConnection`. Click on **Connection Strings** on left menu and copy the **ADO.NET (SQL authentication)** connection string. Populate **User ID={your_username};Password={your_password};** with values your provided during database creation.Copy this connection string.
254279
1. Choose `SQLAzure` in the **Type** dropdown. **Save** the setting.
280+
1. If you want to setup a Redis Cache instead search for `Azure Cache for Redis` and select the matching option from the screen.
281+
1. Follow the steps to create a cache that will meet your needs then press the `Create` button and wait for the cache to be successfully deployed.
282+
1. Wait for the `Deployment succeeded` notification, then click o1 `Go to resource` to navigate to the newly created database's manage screen.
283+
1. Navigate to the `Access Keys` option in the menu on the left. Copy either the `Primary connection string` and `Secondary connection string` values are the connection strings to the Redis database.
284+
1. Update the `TokenCacheRedisConnStr` value in the `appsettings.json` file with either the `Primary connection string` and `Secondary connection string` and be sure that the `TokenCacheRedisInstanceName` value is set. You can even test that sessions are stored to the cache by running the application locally if you wish.
285+
1. Once the web site is created, locate it it in the **Dashboard** and click it to open **App Services** **Overview** screen.
255286
1. 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.
256287
1. Switch to Visual Studio and go to the WebApp-OpenIDConnect-DotNet-code-v2 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.
257288
1. Click on **Configure** and in the `Connection tab`, update the Destination URL so that it is a `https` in the home page url, for example [https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net](https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net). Click **Next**.

2-WebApp-graph-user/2-2-TokenCache/Startup.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ dotnet tool install --global dotnet-sql-cache
6565
options.DefaultSlidingExpiration = TimeSpan.FromMinutes(90);
6666
});
6767

68-
// Uncomment for Redis configuration
68+
// Uncomment for Redis configuration. Be sure you DO NOT ADD BOTH an SQL cache and Redis cache
6969
//services.AddStackExchangeRedisCache(options =>
7070
//{
71-
// options.Configuration = "localhost";//Configuration.GetConnectionString("TokenCacheRedisConnStr");
72-
// options.InstanceName = Configuration.GetConnectionString("TokenCacheRedisInstaceName");
71+
// options.Configuration = Configuration.GetConnectionString("TokenCacheRedisConnStr");
72+
// options.InstanceName = Configuration.GetConnectionString("TokenCacheRedisInstanceName");
7373
//});
7474

7575

2-WebApp-graph-user/2-2-TokenCache/appsettings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"ConnectionStrings": {
2929
"TokenCacheDbConnStr": "[Enter the Sql server connection string, e.g. Server=MY_SQL_SERVER;Database=MsalTokenCacheDatabase;Trusted_Connection=True;",
3030
"TokenCacheRedisConnStr": "[Replace with your domain like so: <your-domain>.redis.cache.windows.net:6380,password=SomeLongPassword,ssl=True,abortConnect=False or with 'localhost' if running locally]",
31-
"TokenCacheRedisInstaceName": "[Replace with your instance name]"
31+
"TokenCacheRedisInstanceName": "[Replace with your instance name]"
3232
},
3333
"Logging": {
3434
"LogLevel": {

0 commit comments

Comments
 (0)