Build .NET apps with Microsoft Graph and app-only authentication
This tutorial teaches you how to build a .NET console app that uses the Microsoft Graph API to access data using app-only authentication. App-only authentication is a good choice for background services or applications that need to access data for all users in an organization.
Note
To learn how to use Microsoft Graph to access data on behalf of a user, see this user (delegated) authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have the .NET SDK installed on your development machine.
You should also have a Microsoft work or school account with the Global administrator role. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a 1-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with .NET SDK version 7.0.102. The steps in this guide may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Azure Active Directory to enable app-only authentication. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Register application for app-only authentication
In this section you will register an application that supports app-only authentication using client credentials flow.
Open a browser and navigate to the Microsoft Entra admin center and login using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph App-Only Auth Tutorial
.Set Supported account types to Accounts in this organizational directory only.
Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them, you will need these values in the next step.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.
Select Certificates and secrets under Manage, then select New client secret.
Enter a description, choose a duration, and select Add.
Copy the secret from the Value column, you will need it in the next steps.
Important
This client secret is never shown again, so make sure you copy it now.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. This is because app-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
Create a .NET console app
Begin by creating a new .NET console project using the .NET CLI.
Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command.
dotnet new console -o GraphAppOnlyTutorial
Once the project is created, verify that it works by changing the current directory to the GraphTutorial directory and running the following command in your CLI.
dotnet run
If it works, the app should output
Hello, World!
.
Install dependencies
Before moving on, add some additional dependencies that you will use later.
- .NET configuration packages to read application configuration from appsettings.json.
- Azure Identity client library for .NET to authenticate the user and acquire access tokens.
- Microsoft Graph .NET client library to make calls to the Microsoft Graph.
Run the following commands in your CLI to install the dependencies.
dotnet add package Microsoft.Extensions.Configuration.Binder
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.UserSecrets
dotnet add package Azure.Identity
dotnet add package Microsoft.Graph
Load application settings
In this section you'll add the details of your app registration to the project.
Create a file in the GraphAppOnlyTutorial directory named appsettings.json and add the following code.
{ "settings": { "clientId": "YOUR_CLIENT_ID_HERE", "tenantId": "YOUR_TENANT_ID_HERE" } }
Update the values according to the following table.
Setting Value clientId
The client ID of your app registration tenantId
The tenant ID of your organization. Tip
Optionally, you can set these values in a separate file named appsettings.Development.json.
Add your client secret to the .NET Secret Manager. In your command-line interface, change the directory to the location of GraphAppOnlyTutorial.csproj and run the following commands, replacing <client-secret> with your client secret.
dotnet user-secrets init dotnet user-secrets set settings:clientSecret <client-secret>
Update GraphAppOnlyTutorial.csproj to copy appsettings.json to the output directory. Add the following code between the
<Project>
and</Project>
lines.<ItemGroup> <None Include="appsettings*.json"> <CopyToOutputDirectory>Always</CopyToOutputDirectory> </None> </ItemGroup>
Create a file in the GraphAppOnlyTutorial directory named Settings.cs and add the following code.
using Microsoft.Extensions.Configuration; public class Settings { public string? ClientId { get; set; } public string? ClientSecret { get; set; } public string? TenantId { get; set; } public static Settings LoadSettings() { // Load settings IConfiguration config = new ConfigurationBuilder() // appsettings.json is required .AddJsonFile("appsettings.json", optional: false) // appsettings.Development.json" is optional, values override appsettings.json .AddJsonFile($"appsettings.Development.json", optional: true) // User secrets are optional, values override both JSON files .AddUserSecrets<Program>() .Build(); return config.GetRequiredSection("Settings").Get<Settings>() ?? throw new Exception("Could not load app settings. See README for configuration instructions."); } }
Design the app
In this section you will create a simple console-based menu.
Open ./Program.cs and replace its entire contents with the following code.
Console.WriteLine(".NET Graph App-only Tutorial\n"); var settings = Settings.LoadSettings(); // Initialize Graph InitializeGraph(settings); int choice = -1; while (choice != 0) { Console.WriteLine("Please choose one of the following options:"); Console.WriteLine("0. Exit"); Console.WriteLine("1. Display access token"); Console.WriteLine("2. List users"); Console.WriteLine("3. Make a Graph call"); try { choice = int.Parse(Console.ReadLine() ?? string.Empty); } catch (System.FormatException) { // Set to invalid value choice = -1; } switch(choice) { case 0: // Exit the program Console.WriteLine("Goodbye..."); break; case 1: // Display access token await DisplayAccessTokenAsync(); break; case 2: // List users await ListUsersAsync(); break; case 3: // Run any Graph code await MakeGraphCallAsync(); break; default: Console.WriteLine("Invalid choice! Please try again."); break; } }
Add the following placeholder methods at the end of the file. You'll implement them in later steps.
void InitializeGraph(Settings settings) { // TODO } async Task DisplayAccessTokenAsync() { // TODO } async Task ListUsersAsync() { // TODO } async Task MakeGraphCallAsync() { // TODO }
This implements a basic menu and reads the user's choice from the command line.
Add app-only authentication
In this section you will add app-only authentication to the application. This is required to obtain the necessary OAuth access token to call the Microsoft Graph. In this step you will integrate the Azure Identity client library for .NET into the application and configure authentication for the Microsoft Graph .NET client library.
The Azure Identity library provides a number of TokenCredential
classes that implement OAuth2 token flows. The Microsoft Graph client library uses those classes to authenticate calls to Microsoft Graph.
Configure Graph client for app-only authentication
In this section you will use the ClientSecretCredential
class to request an access token by using the client credentials flow.
Create a new file in the GraphTutorial directory named GraphHelper.cs and add the following code to that file.
using Azure.Core; using Azure.Identity; using Microsoft.Graph; using Microsoft.Graph.Models; class GraphHelper { }
Add the following code to the
GraphHelper
class.// Settings object private static Settings? _settings; // App-ony auth token credential private static ClientSecretCredential? _clientSecretCredential; // Client configured with app-only authentication private static GraphServiceClient? _appClient; public static void InitializeGraphForAppOnlyAuth(Settings settings) { _settings = settings; // Ensure settings isn't null _ = settings ?? throw new System.NullReferenceException("Settings cannot be null"); _settings = settings; if (_clientSecretCredential == null) { _clientSecretCredential = new ClientSecretCredential( _settings.TenantId, _settings.ClientId, _settings.ClientSecret); } if (_appClient == null) { _appClient = new GraphServiceClient(_clientSecretCredential, // Use the default scope, which will request the scopes // configured on the app registration new[] {"https://graph.microsoft.com/.default"}); } }
Replace the empty
InitializeGraph
function in Program.cs with the following.void InitializeGraph(Settings settings) { GraphHelper.InitializeGraphForAppOnlyAuth(settings); }
This code declares two private properties, a ClientSecretCredential
object and a GraphServiceClient
object. The InitializeGraphForAppOnlyAuth
function creates a new instance of ClientSecretCredential
, then uses that instance to create a new instance of GraphServiceClient
. Every time an API call is made to Microsoft Graph through the _appClient
, it uses the provided credential to get an access token.
Test the ClientSecretCredential
Next, add code to get an access token from the ClientSecretCredential
.
Add the following function to the
GraphHelper
class.public static async Task<string> GetAppOnlyTokenAsync() { // Ensure credential isn't null _ = _clientSecretCredential ?? throw new System.NullReferenceException("Graph has not been initialized for app-only auth"); // Request token with given scopes var context = new TokenRequestContext(new[] {"https://graph.microsoft.com/.default"}); var response = await _clientSecretCredential.GetTokenAsync(context); return response.Token; }
Replace the empty
DisplayAccessTokenAsync
function in Program.cs with the following.async Task DisplayAccessTokenAsync() { try { var appOnlyToken = await GraphHelper.GetAppOnlyTokenAsync(); Console.WriteLine($"App-only token: {appOnlyToken}"); } catch (Exception ex) { Console.WriteLine($"Error getting app-only access token: {ex.Message}"); } }
Build and run the app. Enter
1
when prompted for an option. The application displays an access token..NET Graph Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 1 App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...
Tip
For validation and debugging purposes only, you can decode app-only access tokens using Microsoft's online token parser at https://jwt.ms. This can be useful if you encounter token errors when calling Microsoft Graph. For example, verifying that the
role
claim in the token contains the expected Microsoft Graph permission scopes.
List users
In this section you will add the ability to list all users in your Azure Active Directory using app-only authentication.
Open ./GraphHelper.cs and add the following function to the GraphHelper class.
public static Task<UserCollectionResponse?> GetUsersAsync() { // Ensure client isn't null _ = _appClient ?? throw new System.NullReferenceException("Graph has not been initialized for app-only auth"); return _appClient.Users.GetAsync((config) => { // Only request specific properties config.QueryParameters.Select = new[] { "displayName", "id", "mail" }; // Get at most 25 results config.QueryParameters.Top = 25; // Sort by display name config.QueryParameters.Orderby = new[] { "displayName" }; }); }
Replace the empty
ListUsersAsync
function in Program.cs with the following.async Task ListUsersAsync() { try { var userPage = await GraphHelper.GetUsersAsync(); if (userPage?.Value == null) { Console.WriteLine("No results returned."); return; } // Output each users's details foreach (var user in userPage.Value) { Console.WriteLine($"User: {user.DisplayName ?? "NO NAME"}"); Console.WriteLine($" ID: {user.Id}"); Console.WriteLine($" Email: {user.Mail ?? "NO EMAIL"}"); } // If NextPageRequest is not null, there are more users // available on the server // Access the next page like: // var nextPageRequest = new UsersRequestBuilder(userPage.OdataNextLink, _appClient.RequestAdapter); // var nextPage = await nextPageRequest.GetAsync(); var moreAvailable = !string.IsNullOrEmpty(userPage.OdataNextLink); Console.WriteLine($"\nMore users available? {moreAvailable}"); } catch (Exception ex) { Console.WriteLine($"Error getting users: {ex.Message}"); } }
Run the app and choose option 2 to list users.
Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: [email protected] User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: [email protected] User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: [email protected] User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: [email protected] ... More users available? True
Code explained
Consider the code in the GetUsersAsync
function.
- It gets a collection of users
- It uses
Select
to request specific properties - It uses
Top
to limit the number of users returned - It uses
OrderBy
to sort the response
Optional: add your own code
In this section you will add your own Microsoft Graph capabilities to the application. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Update the app
Open ./GraphHelper.cs and add the following function to the GraphHelper class.
// This function serves as a playground for testing Graph snippets // or other code public async static Task MakeGraphCallAsync() { // INSERT YOUR CODE HERE }
Replace the empty
MakeGraphCallAsync
function in Program.cs with the following.async Task MakeGraphCallAsync() { await GraphHelper.MakeGraphCallAsync(); }
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the Create event API. You can use one of the examples in the API documentation, or you can customize an example.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, or personal Microsoft accounts, for example.
- To call an API with user authentication (if the API supports user (delegated) authentication), see the user (delegated) authentication tutorial.
- To call an API with app-only authentication (if the API supports it), add the required permission scope in the Azure AD admin center.
Add your code
Copy your code into the MakeGraphCallAsync
function in GraphHelper.cs. If you're copying a snippet from documentation or Graph Explorer, be sure to rename the GraphServiceClient
to _appClient
.
Congratulations!
You've completed the .NET Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features.
- Learn how to use user (delegated) authentication with the Microsoft Graph .NET SDK.
- Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
.NET samples
Have an issue with this section? If so, please give us some feedback so we can improve this section.