| services | active-directory |
|---|---|
| platforms | dotnet |
| author | kalyankrishna1 |
| level | 200 |
| client | ASP.NET Core Web App |
| service | Microsoft Graph |
| endpoint | Microsoft identity platform |
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.
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.
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/active-directory-aspnetcore-webapp-openidconnect-v2.gitor download and extract the repository .zip file.
Given that the name of the sample is quiet long, and so are the names 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.
There is one project in this sample. To register it, you can:
- either follow the steps Step 2: Register the sample with your Azure Active Directory tenant and Step 3: Configure the sample to use your Azure AD tenant
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you
- modify the Visual Studio projects' configuration files.
If you want to use this automation:
-
On Windows, run PowerShell and navigate to the root of the cloned directory
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
In PowerShell run:
.\AppCreationScripts\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts
-
Open the Visual Studio solution and click start to run the code.
If you don't want to use this automation, follow the steps below.
As a first step you'll need to:
- Sign in to the Azure portal using either a work or school account or a personal Microsoft account.
- If your account is present in more than one Azure AD tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory. Change your portal session to the desired Azure AD tenant.
-
Navigate to the Microsoft identity platform for developers App registrations page.
-
Select New registration.
-
When the Register an application page appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
WebApp-OpenIDConnect-DotNet-code-v2. - Change Supported account types to Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com).
Note that there are more than one redirect URIs. You'll need to add them from the Authentication tab later after the app has been created successfully.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
-
Select Register to create the application.
-
On the app Overview page, find the Application (client) ID value and record it for later. You'll need it to configure the Visual Studio configuration file for this project.
-
From the app's Overview page, select the Authentication section.
- In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.
https://localhost:44321/https://localhost:44321/signin-oidc
- In the Advanced settings section set Logout URL to
https://localhost:44321/signout-oidc - In the Advanced settings | Implicit grant section, check ID tokens as this sample requires the Implicit grant flow to be enabled to sign-in the user, and call an API.
- In the Redirect URIs section, select Web in the combo-box and enter the following redirect URIs.
-
Select Save.
-
From the Certificates & secrets page, in the Client secrets section, choose New client secret:
- Type a key description (of instance
app secret), - Select a key duration of either In 1 year, In 2 years, or Never Expires.
- When you press the Add button, the key value will be displayed, copy, and save the value in a safe location.
- You'll need this key later to configure the project in Visual Studio. This key value will not be displayed again, nor retrievable by any other means, so record it as soon as it is visible from the Azure portal.
- Type a key description (of instance
-
Select the API permissions section
- Click the Add a permission button and then,
- Ensure that the Microsoft APIs tab is selected
- In the Commonly used Microsoft APIs section, click on Microsoft Graph
- In the Delegated permissions section, ensure that the right permissions are checked: User.Read. Use the search box if necessary.
- Select the Add permissions button
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the solution in Visual Studio to configure the projects
Note: if you had used the automation to setup your application mentioned in Step 2: Register the sample application with your Azure Active Directory tenant, the changes below would have been applied by the scripts.
- Open the
appsettings.jsonfile - Find the app key
ClientIdand replace the existing value with the application ID (clientId) of theWebApp-OpenIDConnect-DotNet-code-v2application copied from the Azure portal. - Find the app key
TenantIdand replace the existing value with your Azure AD tenant ID. - Find the app key
Domainand replace the existing value with your Azure AD tenant name. - Find the app key
ClientSecretand replace the existing value with the key you saved during the creation of theWebApp-OpenIDConnect-DotNet-code-v2app, in the Azure portal.
In the appsettings.json file, configure a Sql server database for token caching, if you have not already done so:
-
In the
TokenCacheDbConnStrkey, 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, you can execute the
dotnet sql-cache createcommand to create the table for you. To do that, follow the steps below.dotnet tool install --global dotnet-sql-cache dotnet sql-cache create "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MY_TOKEN_CACHE_DATABASE;Integrated Security=True;" dbo TokenCache
-
In case you want to deploy your app in Sovereign or national clouds, ensure the
GraphApiUrloption 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.AddMicrosoftIdentityPlatformAuthentication(Configuration)
.AddMsal(Configuration, new string[] { Constants.ScopeUserRead })
.AddDistributedTokenCaches();
services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = Configuration.GetConnectionString("TokenCacheDbConnStr");
options.SchemaName = "dbo";
options.TableName = "TokenCache";
});The aforementioned 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
TokenCacheDbConnStravailable 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.
- 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
This project has one WebApp project. To deploy it to the Azure Web Site, you'll need to:
- create an Azure Web Site
- publish the Web App to the web site, and
- update its client(s) to call the web site instead of IIS Express.
- Sign in to the Azure portal.
- Click
Create a resourcein the top left-hand corner, select Web --> Web App, and give your web site a name, for example,WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net. - Thereafter select the
Subscription,Resource Group,App service plan and Location.OSwill be Windows andPublishwill be Code. - Click
Createand wait for the App Service to be created. - Once you get the
Deployment succeedednotification, then click onGo to resourceto navigate to the newly created App service. - 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. - Click
Create a resourcein the top left-hand corner again, select Databases --> SQL Database, to create a new database. Follow theQuickstart tutorialif needed. - You can name the Sql server and database whatever you want to.
- 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.
- Wait for the
Deployment succeedednotification, then click onGo to resourceto navigate to the newly created database's manage screen. - 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.
- Once the web site is created, locate it it in the Dashboard and click it to open App Services Overview screen.
- 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. - Choose
SQLAzurein the Type dropdown. Save the setting. - 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.
- 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.
- Click on Configure and in the
Connection tab, update the Destination URL so that it is ahttpsin the home page url, for example https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authenticationis NOT selected. Click Save. Click on Publish on the main screen. - Visual Studio will publish the project and automatically open a browser to the URL of the project. If you see the default web page of the project, the publication was successful.
- Navigate back to to the Azure portal. In the left-hand navigation pane, select the Azure Active Directory service, and then select App registrations (Preview).
- In the resultant screen, select the
WebApp-OpenIDConnect-DotNet-code-v2application. - In the Authentication | page for your application, update the Logout URL fields with the address of your service, for example https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net
- From the Branding menu, update the Home page URL, to the address of your service, for example https://WebApp-OpenIDConnect-DotNet-code-v2-contoso.azurewebsites.net. Save the configuration.
- Add the same URL in the list of values of the Authentication -> Redirect URIs menu. If you have multiple redirect urls, make sure that there a new entry using the App service's Uri for each redirect url.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-active-directory msal dotnet].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.
If you'd like to contribute to this sample, see CONTRIBUTING.MD.
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
