services | platforms | author | level | client | service | endpoint |
---|---|---|---|---|---|---|
active-directory |
dotnet |
kalyankrishna1 |
200 |
ASP.NET Core 2.x Web App |
Microsoft Graph |
Microsoft identity platform |
Call the Microsoft Graph API from an An ASP.NET Core 2.x Web App, using Sql Server for caching tokens
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.
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.
To run this sample, you'll need:
- Visual Studio 2017 or just the .NET Core SDK
- An Internet connection
- A Windows machine (necessary if you want to run the app on Windows)
- An OS X machine (necessary if you want to run the app on Mac)
- A Linux machine (necessary if you want to run the app on Linux)
- 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/microsoft-identity-platform-aspnetcore-webapp-tutorial webapp
cd webapp
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.
Go to the "2-WebApp-graph-user\2-2-TokenCache"
folder
cd "2-WebApp-graph-user\2-2-TokenCache"
In the appsettings.json file, configure a Sql server database for token caching, if you have not already done so:
- In the
TokenCacheDbConnStr
key, provide the Sql server connection string to the database you wish to use for token caching.Note: If you want to test this sample locally with Visual Studio, you might want to use localdb, which is installed with Visual Studio. In that case, use the following connection string:
"ConnectionStrings": { "TokenCacheDbConnStr": "Data Source=(LocalDb)\\MSSQLLocalDB;Database=MY_TOKEN_CACHE_DATABASE;Trusted_Connection=True;" },
- If you do not have an existing database and tables needed for token caching, this sample can use EF Core- code first to create a database and tables for you. to do that, follow the steps below.
- In the file
Microsoft.Identity.Web\Client\TokenCacheProviders\Sql\MSALAppSqlTokenCacheProviderExtension.cs
, uncomment the code under the // Uncomment the following lines to create the database.. This comment exists once in the AddSqlAppTokenCache and AddSqlPerUserTokenCache methods. - Run the solution again, when a user signs-in the very first time, the Entity Framework will create the database and tables
AppTokenCache
andUserTokenCache
for app and user token caching respectively.
- In the file
-
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"GraphApiUrl": "https://graph.microsoft.com"
-
Clean the solution, rebuild the solution, and run it.
-
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.
-
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)
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 page.
Starting from the previous phase of the tutorial, the code was incrementally updated with the following steps:
public void ConfigureServices(IServiceCollection services)
{
. . .
// Token acquisition service based on MSAL.NET
// and the Sql server based token cache implementation
services.AddAzureAdV2Authentication(Configuration)
.AddMsal(new string[] { Constants.ScopeUserRead })
.AddSqlAppTokenCache(Configuration)
.AddSqlPerUserTokenCache(Configuration);
The aforementioned four lines of code are explained below.
- 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.
- 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.
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.
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.
services.AddDataProtection()
.SetApplicationName("WebApp_Tutorial");
- Learn how to enable distributed caches in token cache serialization
- Learn how the same principle you've just learnt can be used to call:
- several Microsoft APIs, which will enable you to learn how incremental consent and conditional access is managed in your Web App
- 3rd party, or even your own Web API, which will enable you to learn about custom scopes
- Learn how Microsoft.Identity.Web works, in particular hooks-up to the ASP.NET Core ODIC events
- Use HttpClientFactory to implement resilient HTTP requests used by the Graph custom service