services | platforms | author | level | client | service | endpoint | page_type | languages | products | description | |||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
active-directory |
dotnet |
TiagoBrenck |
400 |
.NET Framework Desktop |
ASP.NET Web API, Microsoft Graph API |
Microsoft identity platform |
sample |
|
|
This sample demonstrates a .NET Framework Desktop application calling an ASP.NET Web API, Microsoft Graph API that is secured with the Microsoft identity platform |
Call a downstream web API (Microsoft Graph) from a web API secured with the Microsoft identity platform (Azure Active Directory) using the On-Behalf-Of flow
We have renamed the default branch to main. To rename your local repo follow the directions here.
This sample demonstrates a .NET Framework Desktop app calling an ASP.NET Web API, which in turn calls the Microsoft Graph API using an access token obtained using the on-behalf-of flow. All these are secured using the Microsoft identity platform (formerly Azure Active Directory for developers)
- The .Net client desktop application uses the Microsoft Authentication Library (MSAL) to obtain an access token for the ASP.NET Web Api from the Microsoft identity platform for the authenticated user.
- The access token is then used as a bearer token to authorize the caller in the ASP.NET Web API and then subsequently for Microsoft Graph API.
The flow is as follows:
- Sign-in to the client application.
- Acquire a token for the Asp.net Web API (
TodoListService
) and call it. - The Asp.Net Web API authorizes the caller, obtains another access token using the on-behalf-of flow and then calls another downstream Web API (Microsoft Graph).
The TodoListService (the Asp.net Web API) uses a database to:
-
Store the ToDo list.
-
It also illustrates the token cache serialization in a service.
TodoListClient
uses MSAL.NET to acquire an access token for the user in order to call TodoListService Web API. For more information about how to acquire tokens interactively, see Acquiring tokens interactively with Public client application flows.- Then
TodoListService
also uses MSAL.NET to get another access token using the on-behalf-of flow to call the Microsoft Graph. For details, see Service to service calls on behalf of the user.
Developers who wish to gain good familiarity of programming for Microsoft Graph are advised to go through the An introduction to Microsoft Graph for developers recorded session.
Both flows use the OAuth 2.0 protocol to obtain the tokens. For more information about how the protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
To run this sample, you'll need:
- Visual Studio 2019
- An Internet connection
- 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/ms-identity-aspnet-webapi-onbehalfof.git
or download and extract the repository .zip file.
⚠️ Given that the name of the sample is quite long, and so are the names of the referenced packages, you might want to clone it in a folder close to the root of your hard drive, to avoid maximum file path length limitations on Windows.
There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can:
- either follow the steps Step 2: Register the sample application with your Azure Active Directory tenant and Step 3: Configure the sample application to use your Azure Active Directory tenant
- or use PowerShell scripts that:
- automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you. Note that this works for Visual Studio only.
- modify the Visual Studio projects' configuration files.
Expand this section 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:
cd .\AppCreationScripts\ .\Configure.ps1
Other ways of running the scripts are described in App Creation Scripts The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
-
Open the Visual Studio solution and click start to run the code.
Follow the steps below to manually walk through the steps to register and configure the applications.
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.
- In the Register an application page that 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
TodoListService-OBO-sample-v2
. - Under Supported account types, select Accounts in this organizational directory only.
- 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.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
- In the app's registration screen, click on the Certificates & secrets blade in the left to open the page where we can generate secrets and upload certificates.
- In the Client secrets section, click on New client secret:
- Type a key description (for instance
app secret
), - Select one of the available key durations (In 1 year, In 2 years, or Never Expires) as per your security posture.
- The generated key value will be displayed when you click the Add button. Copy the generated value for use in the steps later.
- You'll need this key later in your code's configuration files. This key value will not be displayed again, and is not retrievable by any other means, so make sure to note it from the Azure portal before navigating to any other screen or blade.
- Type a key description (for instance
- In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- 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, select the User.Read in the list. Use the search box if necessary.
- Click on the Add permissions button at the bottom.
- In the app's registration screen, select the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an Api for which client applications can obtain access tokens for.
The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this Api. To declare an resource URI, follow the following steps:
- Click
Set
next to the Application ID URI to generate a URI that is unique for this app. - For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting Save.
- Click
- All Apis have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
access_as_user
. - Select Admins and users options for Who can consent?
- For Admin consent display name type
Access TodoListService-OBO-sample-v2
- For Admin consent description type
Allows the app to access TodoListService-OBO-sample-v2 as the signed-in user.
- For User consent display name type
Access TodoListService-OBO-sample-v2
- For User consent description type
Allow the application to access TodoListService-OBO-sample-v2 on your behalf.
- Keep State as Enabled
- Click on the Add scope button on the bottom to save this scope.
- For Scope name, use
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
TodoListService\Web.Config
file - Find the app key
ida:Tenant
and replace the existing value with your Azure AD tenant name. - Find the app key
ida:Audience
and replace the existing value with the App ID URI you registered earlier, when exposing an API. For instance useapi://<application_id>
. - Find the app key
ida:AppKey
and replace the existing value with the key you saved during the creation of theTodoListService-OBO-sample-v2
app, in the Azure portal. - Find the app key
ida:ClientID
and replace the existing value with the application ID (clientId) of theTodoListService-OBO-sample-v2
application copied from the Azure portal.
- Navigate to the Microsoft identity platform for developers App registrations page.
- Select New registration.
- In the Register an application page that 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
TodoListClient-OBO-sample-v2
. - Under Supported account types, select Accounts in this organizational directory only.
- 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.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- In the app's registration screen, select Authentication in the menu.
- If you don't have a platform added, select Add a platform and select the Public client (mobile & desktop) option.
- In the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, select https://login.microsoftonline.com/common/oauth2/nativeclient
- Select Save to save your changes.
- In the app's registration screen, click on the API permissions blade in the left to open the page where we add access to the APIs that your application needs.
- Click the Add a permission button and then,
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
TodoListService-OBO-sample-v2
. - In the Delegated permissions section, select the Access 'TodoListService-OBO-sample-v2' in the list. Use the search box if necessary.
- Click on the Add permissions button at the bottom.
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
- Open the
TodoListClient\App.Config
file - Find the app key
ida:Tenant
and replace the existing value with your Azure AD tenant name. - Find the app key
ida:ClientId
and replace the existing value with the application ID (clientId) of theTodoListClient-OBO-sample-v2
application copied from the Azure portal. - Find the app key
todo:TodoListScope
and replace the existing value with the default scope. The default scope is created by appending/.default
to the service's App ID URL (e.g.api://a0000001-000a-000a-000a-00000000000a/.default
), and is explained further below. - Find the app key
todo:TodoListBaseAddress
and replace the existing value with the base address of the TodoListService-OBO-sample-v2 project (by defaulthttps://localhost:44321/
).
For a middle tier Web API (TodoListService-OBO-sample-v2
) to be able to call a downstream Web API, the middle tier app needs to be granted the required permissions as well.
However, since the middle tier cannot interact with the signed-in user, it needs to be explicitly bound to the client app in its Azure AD registration.
This binding merges the permissions required by both the client and the middle tier Web Api and presents it to the end user in a single consent dialog. The user then consent to this combined set of permissions.
To achieve this, you need to add the Application Id of the client app, in the Manifest of the Web API in the knownClientApplications
property. Here's how:
-
In the Azure portal, navigate to your
TodoListService-OBO-sample-v2
app registration, and select Manifest section. -
In the manifest editor, change the
"knownClientApplications": []
line so that the array contains the Client ID of the client application (TodoListClient-OBO-sample-v2
) as an element of the array.For instance:
"knownClientApplications": ["ca8dca8d-f828-4f08-82f5-325e1a1c6428"],
-
Save the changes to the manifest.
Clean the solution, rebuild the solution, and run it. You might want to go into the solution properties and set both projects as startup projects, with TodoListService starting first.
Explore the sample by signing-in, adding items to the To-do list, clearing the cache (which removes the user account), and starting again. The To-do list service will take the user's access token, received from the client, and use it to get another access token so it can act on behalf of the user in the Microsoft Graph API.
This sample caches the user's access token in the To-do list service, so it does not request a new access token on every request. This cache is stored in a database.
There are many key points in this sample to make the on-behalf-of flow (OBO) to work properly and in this section we will explain these key points for each project.
In this project, users can sign-in and interact with the Web API (TodoListService). The first key point to pay attention is the MainWindow
initialization. Here is the code snippet:
private readonly IPublicClientApplication _app;
public MainWindow()
{
InitializeComponent();
_app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.Build();
TokenCacheHelper.EnableSerialization(_app.UserTokenCache);
GetTodoList();
}
Important things to notice:
- We create an
IPublicClientApplication
passing theclientId
andauthority
in the builder. ThisIPublicClientApplication
will be responsible of acquiring access tokens later in the code. IPublicClientApplication
also has a token cache, that will cache access tokens and refresh tokens for the signed-in user. This is done so that the application can fetch access tokens after they have expired without prompting the user to sign-in again.- Our
UserTokenCache
implementation uses the local file system for caching. Other popular options for caching tokens aredatabase
ordistributed in-memory cache
.
When the SignIn
method is called, the login screen is presented so the user can provide their credentials.
private static readonly string[] Scopes = { "api://<service_application_id>/.default" };
private async void SignIn(object sender = null, RoutedEventArgs args = null)
{
AuthenticationResult result = await _app.AcquireTokenInteractive(Scopes)
.WithAccount(accounts.FirstOrDefault())
.WithPrompt(Prompt.SelectAccount)
.ExecuteAsync()
.ConfigureAwait(false);
}
Important things to notice:
- The scope
.default
is a built-in scope for every application that refers to the static list of permissions configured on the application registration. In our scenario, it enables the user to grant consent for both the Web API and the downstream API (Microsoft Graph) permissions. For example, the permissions for the Web API and the downstream API (Microsoft Graph) are listed below:- TodoListService-OBO-sample-v2
- access_as_user
- Microsoft Graph
- user.read
- TodoListService-OBO-sample-v2
- The method AcquireTokenInteractive will acquire an access token for TodoListService-OBO-sample and MSAL will save this token in its token cache.
The method to add a new To-do is where the TodoListService-OBO Web API is consumed, which will call a downstream API, Microsoft Graph, using the on-behalf-of flow (OBO).
To check if the user is signed in, we use the method GetAccountsAsync:
var accounts = (await _app.GetAccountsAsync()).ToList();
if (!accounts.Any())
{
MessageBox.Show("Please sign in first");
return;
}
Then, we call the AcquireTokenSilent
method to get the cached access token that we obtained earlier during the sign-in. This access token will be sent in the HTTP header of the Web API request as a bearer token
.
AuthenticationResult result = null;
try
{
result = await _app.AcquireTokenSilent(Scopes, accounts.FirstOrDefault())
.ExecuteAsync()
.ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
MessageBox.Show("Please re-sign");
}
catch (MsalException ex)
{
// An unexpected error occurred.
}
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("Title", TodoText.Text) });
HttpResponseMessage response = await httpClient.PostAsync(todoListBaseAddress + "/api/todolist", content);
if (response.IsSuccessStatusCode)
{
TodoText.Text = "";
GetTodoList();
}
else
{
MessageBox.Show("An error occurred : " + response.ReasonPhrase);
}
Important things to notice:
- After the Sign-In, the access token will be cached and it can be acquired by calling AcquireTokenSilent.
MsalUiRequiredException
will be thrown if there are no tokens for that user with the specified scope in the cache, or it got expired. This case requires the user to Sign-In again.
The TodoListService is our Web API project that will make a call to the downstream Microsoft Graph API using an access token obtained via the on-behalf-of flow. The client that called TodoListService, sends a Bearer token
on the HTTP header and this token will be used to impersonate the user and acquire another access token for Microsoft Graph API.
The first key point to pay attention in this project is the Startup
configuration:
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
SaveSigninToken = true,
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
}
});
}
Important things to notice:
- Notice that we are setting
SaveSigninToken
totrue
on theTokenValidationParameters
. This is essential to get theBearer token
from the HTTP header later, using the identity bootstrap context:ClaimsPrincipal.Current.Identities.First().BootstrapContext
The logic to call Microsoft Graph on behalf of a user is inside the method CallGraphAPIOnBehalfOfUser
. In this sample, we are getting the user's first name and last name and adding them in the to-do's title.
The one thing that you will notice is that we are using a different type of token cache provider in the Web API, which caches tokens in a SQL Server database. The implementation of this caching mechanism is encapsulated in the MSALPerUserSqlTokenCacheProvider
class.
private async Task<UserProfile> CallGraphAPIOnBehalfOfUser()
{
string[] scopes = { "user.read" };
UserProfile profile = null;
try
{
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithClientSecret(appKey)
.WithRedirectUri(redirectUri)
.Build();
MSALPerUserSqlTokenCacheProvider sqlCache = new MSALPerUserSqlTokenCacheProvider(app.UserTokenCache, db, ClaimsPrincipal.Current);
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext.ToString();
UserAssertion userAssertion = new UserAssertion(bootstrapContext, "urn:ietf:params:oauth:grant-type:jwt-bearer");
AuthenticationResult result = await app.AcquireTokenOnBehalfOf(scopes, userAssertion)
.ExecuteAsync();
string accessToken = result.AccessToken;
if (accessToken == null)
{
throw new Exception("Access Token could not be acquired.");
}
string requestUrl = String.Format(CultureInfo.InvariantCulture, graphUserUrl, HttpUtility.UrlEncode(tenant));
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseString = await response.Content.ReadAsStringAsync();
profile = JsonConvert.DeserializeObject<UserProfile>(responseString);
return (profile);
}
throw new Exception("An unexpected error occurred calling the Graph API.");
}
catch (Exception ex)
{
throw ex;
}
}
Important things to notice:
- We are using the scope
user.read
to get the user's profile on Microsoft Graph. - We hook the
ConfidentialClientApplication
UserTokenCache
on ourMSALPerUserSqlTokenCacheProvider
, so we can store the cache on the database. Other alternatives for cache storage could beInMemory
orSession
. - We instantiate a
UserAssertion
using the bearer token sent by the client andurn:ietf:params:oauth:grant-type:jwt-bearer
as assertion type (read more here). This class represents the credential of the user being impersonated. - The method
AcquireTokenOnBehalfOf
will try to get an access token for the impersonated user. If all the validations pass and the impersonated user have consented the requested scope (user.read
on our sample), an access token will be returned and be used on Microsoft Graph request, on behalf of the user.
This project has two WebApp / Web API projects. To deploy them to Azure Web Sites, you'll need, for each one, to:
- create an Azure Web Site
- publish the Web App / Web APIs 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 resource
in the top left-hand corner, select Web --> Web App, and give your web site a name, for example,TodoListService-OBO-sample-v2-contoso.azurewebsites.net
. - Thereafter select the
Subscription
,Resource Group
,App service plan and Location
.OS
will be Windows andPublish
will be Code. - Click
Create
and wait for the App Service to be created. - Once you get the
Deployment succeeded
notification, then click onGo to resource
to 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 resource
in the top left-hand corner again, select Databases --> SQL Database, to create a new database. Follow theQuickstart tutorial
if 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 connection string later.
- Wait for the
Deployment succeeded
notification, then click onGo to resource
to 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 Configuration in the left menu of the App service and add the copied Sql connection string in the Connection strings section as
DefaultConnection
. - Choose
SQLAzure
in 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 TodoListService-OBO-sample-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 ahttps
in the home page url, for example https://TodoListService-OBO-sample-v2-contoso.azurewebsites.net. Click Next. - On the Settings tab, make sure
Enable Organizational Authentication
is NOT selected. - Under Databases, select the connection that you created on Azure Portal (if it does not show on the dropdown, click on the button and add it).
- Make sure
Use this connection string at runtime
andExecute Code First Migrations
are checked. - 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. Give it a minute for the migrations to run. 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.
- In the resultant screen, select the
TodoListService-OBO-sample-v2
application. - From the Branding menu, update the Home page URL, to the address of your service, for example https://TodoListService-OBO-sample-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.
Update the TodoListClient-OBO-sample-v2
to call the TodoListService-OBO-sample-v2
Running in Azure Web Sites
- In Visual Studio, go to the
TodoListClient-OBO-sample-v2
project. - Open
TodoListClient\App.Config
. Only one change is needed - update thetodo:TodoListBaseAddress
key value to be the address of the website you published, for example, https://TodoListService-OBO-sample-v2-contoso.azurewebsites.net. - Run the client! If you are trying multiple different client types (for example, .Net, Windows Store, Android, iOS) you can have them all call this one published web API.
First, in Visual Studio 2017 create an empty solution to host the projects. Then, follow these steps to create each project.
- In Visual Studio 2017, create a new
Visual C#
ASP.NET Web Application (.NET Framework)
project. In the next screen, choose theWeb API
project template. And while on this screen, click the Change Authentication button, select 'Work or School Accounts', 'Cloud - Single Organization', enter the name of your Azure AD tenant. You will be prompted to sign in to your Azure AD tenant. NOTE: You must sign in with a user that is in the tenant; you cannot, during this step, sign in with a Microsoft account. - Add the Microsoft Authentication Library (MSAL) NuGet, Microsoft.Identity.Client, EntityFramework, and Microsoft.AspNet.WebApi.Cors to the project.
- Add reference of the
System.IdentityModel
assembly in the project. - In the
Models
folder, add a new class calledTodoItem.cs
. Copy the implementation of TodoItem from this sample into the class. - In the
Models
folder, add a new class calledUserProfile.cs
. Copy the implementation of UserProfile from this sample into the class. - Create a new folder named
DAL
. In theDAL
folder, add a new class calledTodoListServiceContext.cs
. Copy the implementation of TodoListServiceContext from this sample into the class. - Create a new folder named
Utils
. In theUtils
folder, add three new classes (ClaimConstants.cs
,ClaimsPrincipalExtensions.cs
andMSALPerUserSqlTokenCacheProvider
) and copy their implementations from this sample. - Add a new, empty, Web API 2 Controller called
TodoListController
. - Copy the implementation of the TodoListController from this sample into the controller. Don't forget to add the
[Authorize]
attribute to the class. - In
web.config
make sure that the keyida:AADInstance
,ida:Tenant
,ida:ClientID
, andida:AppKey
exist, and are populated. For the global Azure cloud, the value ofida:AADInstance
ishttps://login.onmicrosoft.com/{0}
. - In
web.config
, in<appSettings>
, create keys forida:GraphUserUrl
and set the its value tohttps://graph.microsoft.com/v1.0/me/
.
- In the solution, create a new Windows --> Windows Classic Desktop -> WPF App(.NET Framework) called TodoListClient.
- Add the Microsoft Authentication Library (MSAL) NuGet, Microsoft.Identity.Client to the project.
- Add assembly references to
System.Net.Http
,System.Web.Extensions
, andSystem.Configuration
. - Add a new class to the project called
TodoItem.cs
. Copy the code from the sample project file of the same name into this class, completely replacing the code in the file in the new project. - Add a new class to the project called
FileCache.cs
. Copy the code from the sample project file of the same name into this class, completely replacing the code in the file in the new project. - Copy the markup from `MainWindow.xaml' in the sample project into the file of the same name in the new project, completely replacing the markup in the file in the new project.
- Copy the code from
MainWindow.xaml.cs
in the sample project into the file of the same name in the new project, completely replacing the code in the file in the new project. - In
app.config
create keys forida:AADInstance
,ida:Tenant
,ida:ClientId
,ida:RedirectUri
,todo:TodoListScope
, andtodo:TodoListBaseAddress
and set them accordingly. For the global Azure cloud, the value ofida:AADInstance
ishttps://login.onmicrosoft.com/{0}
.
Finally, in the properties of the solution itself, set both projects as startup projects.
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 [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 [email protected] with any additional questions or comments.
- Other samples for Microsoft identity platform are available from https://aka.ms/aaddevsamplesv2
- Microsoft identity platform and Implicit grant flow
- Microsoft identity platform and OAuth 2.0 On-Behalf-Of flow
- The conceptual documentation for MSAL.NET is available from https://aka.ms/msalnet
- the documentation for Microsoft identity platform is available from https://aka.ms/aadv2
- Why update to Microsoft identity platform? For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.