Quickstart: Acquire a token and call Microsoft Graph API from a desktop application
In this quickstart, you download and run a code sample that demonstrates how a Universal Windows Platform (UWP) application can sign in users and get an access token to call the Microsoft Graph API.
See How the sample works for an illustration.
Prerequisites
- An Azure account with an active subscription. Create an account for free.
- Visual Studio
Register and download your quickstart app
You have two options to start your quickstart application:
- [Express] Option 1: Register and auto configure your app and then download your code sample
- [Manual] Option 2: Register and manually configure your application and code sample
Option 1: Register and auto configure your app and then download your code sample
- Go to the Azure portal - App registrations quickstart experience.
- Enter a name for your application and select Register.
- Follow the instructions to download and automatically configure your new application.
Option 2: Register and manually configure your application and code sample
Step 1: Register your application
To register your application and add the app's registration information to your solution, follow these steps:
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- Enter a Name for your application, for example
UWP-App-calling-MsGraph
. Users of your app might see this name, and you can change it later. - In the Supported account types section, select Accounts in any organizational directory and personal Microsoft accounts (for example, Skype, Xbox, Outlook.com).
- Select Register to create the application, and then record the Application (client) ID for use in a later step.
- Under Manage, select Authentication.
- Select Add a platform > Mobile and desktop applications.
- Under Redirect URIs, select
https://login.microsoftonline.com/common/oauth2/nativeclient
. - Select Configure.
Step 2: Download the project
Download the UWP sample application
Tip
To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.
Step 3: Configure the project
Extract the .zip archive to a local folder close to the root of your drive. For example, into C:\Azure-Samples.
Open the project in Visual Studio. Install the Universal Windows Platform development workload and any individual SDK components if prompted.
In MainPage.Xaml.cs, change the value of the
ClientId
variable to the Application (Client) ID of the application you registered earlier.private const string ClientId = "Enter_the_Application_Id_here";
You can find the Application (client) ID on the app's Overview pane in the Azure portal (Azure Active Directory > App registrations > {Your app registration}).
Create and then select a new self-signed test certificate for the package:
- In the Solution Explorer, double-click the Package.appxmanifest file.
- Select Packaging > Choose Certificate... > Create....
- Enter a password and then select OK. A certificate called Native_UWP_V2_TemporaryKey.pfx is created.
- Select OK to dismiss the Choose a certificate dialog, and then verify that you see Native_UWP_V2_TemporaryKey.pfx in Solution Explorer.
- In the Solution Explorer, right-click the Native_UWP_V2 project and select Properties.
- Select Signing, and then select the .pfx you created in the Choose a strong name key file drop-down.
Step 4: Run the application
To run the sample application on your local machine:
In the Visual Studio toolbar, choose the right platform (probably x64 or x86, not ARM). The target device should change from Device to Local Machine.
Select Debug > Start Without Debugging.
If you're prompted to do so, you might first need to enable Developer Mode, and then Start Without Debugging again to launch the app.
When the app's window appears, you can select the Call Microsoft Graph API button, enter your credentials, and consent to the permissions requested by the application. If successful, the application displays some token information and data obtained from the call to the Microsoft Graph API.
How the sample works
MSAL.NET
MSAL (Microsoft.Identity.Client) is the library used to sign in users and request security tokens. The security tokens are used to access an API protected by the Microsoft Identity platform. You can install MSAL by running the following command in Visual Studio's Package Manager Console:
Install-Package Microsoft.Identity.Client
MSAL initialization
You can add the reference for MSAL by adding the following code:
using Microsoft.Identity.Client;
Then, MSAL is initialized using the following code:
public static IPublicClientApplication PublicClientApp;
PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.Build();
The value of ClientId
is the Application (client) ID of the app you registered in the Azure portal. You can find this value in the app's Overview page in the Azure portal.
Requesting tokens
MSAL has two methods for acquiring tokens in a UWP app: AcquireTokenInteractive
and AcquireTokenSilent
.
Get a user token interactively
Some situations require forcing users to interact with the Microsoft identity platform through a pop-up window to either validate their credentials or to give consent. Some examples include:
- The first-time users sign in to the application
- When users may need to reenter their credentials because the password has expired
- When your application is requesting access to a resource, that the user needs to consent to
- When two factor authentication is required
authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
.ExecuteAsync();
The scopes
parameter contains the scopes being requested, such as { "user.read" }
for Microsoft Graph or { "api://<Application ID>/access_as_user" }
for custom web APIs.
Get a user token silently
Use the AcquireTokenSilent
method to obtain tokens to access protected resources after the initial AcquireTokenInteractive
method. You don’t want to require the user to validate their credentials every time they need to access a resource. Most of the time you want token acquisitions and renewal without any user interaction
var accounts = await PublicClientApp.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
scopes
contains the scopes being requested, such as{ "user.read" }
for Microsoft Graph or{ "api://<Application ID>/access_as_user" }
for custom web APIs.firstAccount
specifies the first user account in the cache (MSAL supports multiple users in a single app).
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
Try out the Windows desktop tutorial for a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart.
In this quickstart, you download and run a code sample that demonstrates how a Windows Presentation Foundation (WPF) application can sign in users and get an access token to call the Microsoft Graph API. The desktop app you build uses the authorization code flow paired with the Proof Key for Code Exchange (PKCE) standard.
See How the sample works for an illustration.
Prerequisites
- Visual Studio with the Universal Windows Platform development workload installed
Register and download your quickstart app
You have two options to start your quickstart application:
- [Express] Option 1: Register and auto configure your app and then download your code sample
- [Manual] Option 2: Register and manually configure your application and code sample
Option 1: Register and auto configure your app and then download your code sample
- Go to the Azure portal - App registrationsquickstart experience.
- Enter a name for your application and select Register.
- Follow the instructions to download and automatically configure your new application with just one click.
Option 2: Register and manually configure your application and code sample
Step 1: Register your application
To register your application and add the app's registration information to your solution manually, follow these steps:
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- Enter a Name for your application, for example
Win-App-calling-MsGraph
. Users of your app might see this name, and you can change it later. - In the Supported account types section, select Accounts in any organizational directory and personal Microsoft accounts (for example, Skype, Xbox, Outlook.com).
- Select Register to create the application.
- Under Manage, select Authentication.
- Select Add a platform > Mobile and desktop applications.
- In the Redirect URIs section, select
https://login.microsoftonline.com/common/oauth2/nativeclient
and in Custom redirect URIs addms-appx-web://microsoft.aad.brokerplugin/{client_id}
where{client_id}
is the application (client) ID of your application (the same GUID that appears in themsal{client_id}://auth
checkbox). - Select Configure.
Step 2: Download the project
Download the WPF sample application
Tip
To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.
Step 3: Configure the project
Extract the zip file to a local folder close to the root of the disk, for example, C:\Azure-Samples.
Open the project in Visual Studio.
Edit App.Xaml.cs and replace the values of the fields
ClientId
andTenant
with the following code:private static string ClientId = "Enter_the_Application_Id_here"; private static string Tenant = "Enter_the_Tenant_Info_Here";
Where:
Enter_the_Application_Id_here
- is the Application (client) ID for the application you registered.To find the value of Application (client) ID, go to the app's Overview page in the Azure portal.
Enter_the_Tenant_Info_Here
- is set to one of the following options:If your application supports Accounts in this organizational directory, replace this value with the Tenant Id or Tenant name (for example, contoso.microsoft.com)
If your application supports Accounts in any organizational directory, replace this value with
organizations
If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace this value with
common
.To find the values of Directory (tenant) ID and Supported account types, go to the app's Overview page in the Azure portal.
Step 4: Run the application
To build and run the sample application in Visual Studio, select the Debug menu > Start Debugging, or press the F5 key. Your application's MainWindow is displayed.
When the app's main window appears, select the Call Microsoft Graph API button. You'll be prompted to sign in using your Azure Active Directory account (work or school account) or Microsoft account (live.com, outlook.com) credentials.
If you're running the application for the first time, you'll be prompted to provide consent to allow the application to access your user profile and sign you in. After consenting to the requested permissions, the application displays that you've successfully logged in. You should see some basic token information and user data obtained from the call to the Microsoft Graph API.
More information
How the sample works
MSAL.NET
MSAL (Microsoft.Identity.Client) is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. You can install MSAL by running the following command in Visual Studio's Package Manager Console:
Install-Package Microsoft.Identity.Client -IncludePrerelease
MSAL initialization
You can add the reference for MSAL by adding the following code:
using Microsoft.Identity.Client;
Then, initialize MSAL using the following code:
IPublicClientApplication publicClientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.WithAuthority(AzureCloudInstance.AzurePublic, Tenant)
.Build();
Where: | Description |
---|---|
ClientId |
Is the Application (client) ID for the application registered in the Azure portal. You can find this value in the app's Overview page in the Azure portal. |
Requesting tokens
MSAL has two methods for acquiring tokens: AcquireTokenInteractive
and AcquireTokenSilent
.
Get a user token interactively
Some situations require forcing users interact with the Microsoft identity platform through a pop-up window to either validate their credentials or to give consent. Some examples include:
- The first time users sign in to the application
- When users may need to reenter their credentials because the password has expired
- When your application is requesting access to a resource that the user needs to consent to
- When two factor authentication is required
authResult = await app.AcquireTokenInteractive(_scopes)
.ExecuteAsync();
Where: | Description |
---|---|
_scopes |
Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api://<Application ID>/access_as_user" } for custom web APIs. |
Get a user token silently
You don't want to require the user to validate their credentials every time they need to access a resource. Most of the time you want token acquisitions and renewal without any user interaction. You can use the AcquireTokenSilent
method to obtain tokens to access protected resources after the initial AcquireTokenInteractive
method:
var accounts = await app.GetAccountsAsync();
var firstAccount = accounts.FirstOrDefault();
authResult = await app.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
Where: | Description |
---|---|
scopes |
Contains the scopes being requested, such as { "user.read" } for Microsoft Graph or { "api://<Application ID>/access_as_user" } for custom web APIs. |
firstAccount |
Specifies the first user in the cache (MSAL support multiple users in a single app). |
Help and support
If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.
Next steps
Try out the Windows desktop tutorial for a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart.
In this quickstart, you download and run a code sample that demonstrates how an Electron desktop application can sign in users and acquire access tokens to call the Microsoft Graph API.
This quickstart uses the Microsoft Authentication Library for Node.js (MSAL Node) with the authorization code flow with PKCE.
Prerequisites
- Node.js
- Visual Studio Code or another code editor
Register and download the sample application
Follow the steps below to get started.
Step 1: Register the application
To register your application and add the app's registration information to your solution manually, follow these steps:
- Sign in to the Azure portal.
- If you have access to multiple tenants, use the Directories + subscriptions filter
in the top menu to switch to the tenant in which you want to register the application.
- Search for and select Azure Active Directory.
- Under Manage, select App registrations > New registration.
- Enter a Name for your application, for example
msal-node-desktop
. Users of your app might see this name, and you can change it later. - Select Register to create the application.
- Under Manage, select Authentication.
- Select Add a platform > Mobile and desktop applications.
- In the Redirect URIs section, enter
http://localhost
. - Select Configure.
Step 2: Download the Electron sample project
Step 3: Configure the Electron sample project
*Extract the project, open the ms-identity-JavaScript-nodejs-desktop-main folder, and then open .authConfig.js file. Replace the value as follows:
Variable | Description | Example(s) |
---|---|---|
Enter_the_Cloud_Instance_Id_Here |
The Azure cloud instance in which your application is registered | https://login.microsoftonline.com/ (include the trailing forward-slash) |
Enter_the_Tenant_Id_Here |
Tenant ID or Primary domain | contoso.microsoft.com or cbe899ec-5f5c-4efe-b7a0-599505d3d54f |
Enter_the_Application_Id_Here |
Client ID of the application you registered | fa29b4c9-7675-4b61-8a0a-bf7b2b4fda91 |
Enter_the_Redirect_Uri_Here |
Redirect Uri of the application you registered | msalfa29b4c9-7675-4b61-8a0a-bf7b2b4fda91://auth |
Enter_the_Graph_Endpoint_Here |
The Microsoft Graph API cloud instance that your app will call | https://graph.microsoft.com/ (include the trailing forward-slash) |
Your file should look similar to below:
const AAD_ENDPOINT_HOST = "https://login.microsoftonline.com/"; // include the trailing slash
const msalConfig = {
auth: {
clientId: "fa29b4c9-7675-4b61-8a0a-bf7b2b4fda91",
authority: `${AAD_ENDPOINT_HOST}/cbe899ec-5f5c-4efe-b7a0-599505d3d54f`,
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: LogLevel.Verbose,
}
}
}
const GRAPH_ENDPOINT_HOST = "https://graph.microsoft.com/"; // include the trailing slash
const protectedResources = {
graphMe: {
endpoint: `${GRAPH_ENDPOINT_HOST}v1.0/me`,
scopes: ["User.Read"],
}
};
module.exports = {
msalConfig: msalConfig,
protectedResources: protectedResources,
};
Step 4: Run the application
You'll need to install the dependencies of this sample once:
cd ms-identity-javascript-nodejs-desktop-main npm install
Then, run the application via command prompt or console:
npm start
Select Sign in to start the sign-in process.
The first time you sign in, you're prompted to provide your consent to allow the application to sign you in and access your profile. After you're signed in successfully, you'll be redirected back to the application.
More information
How the sample works
When a user selects the Sign In button for the first time, acquireTokenInteractive
method of MSAL Node is called. This method redirects the user to sign-in with the Microsoft identity platform endpoint, obtains an authorization code, and then exchanges it for an access token.
MSAL Node
MSAL Node is the library used to sign in users and request tokens used to access an API protected by Microsoft identity platform. For more information on how to use MSAL Node with desktop apps, see this article.
You can install MSAL Node by running the following npm command.
npm install @azure/msal-node --save
Next steps
To learn more about Electron desktop app development with MSAL Node, see the tutorial:
Feedback
Submit and view feedback for