Edit

Share via


Build .NET apps with Microsoft Graph

This tutorial teaches you how to build a .NET console app that uses the Microsoft Graph API to access data on behalf of a user.

Note

To learn how to use Microsoft Graph to access data using app-only authentication, see this app-only authentication tutorial.

In this tutorial, you will:

Tip

As an alternative to following this tutorial, you can download the completed code through the quick start tool, which automates app registration and configuration. The downloaded code works without any modifications required.

You can also 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 an Exchange Online mailbox. 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 one-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 might work with other versions, but that hasn't been tested.

Register an application for user authentication

Register an application that supports user authentication using device code flow. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.

  1. Open a browser and navigate to the Microsoft Entra admin center and sign in using a Global administrator account.

  2. Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.

    A screenshot of the App registrations

  3. Select New registration. Enter a name for your application, for example, Graph User Auth Tutorial.

  4. Set Supported account types as desired. The options are:

    Option Who can sign in?
    Accounts in this organizational directory only Only users in your Microsoft 365 organization
    Accounts in any organizational directory Users in any Microsoft 365 organization (work or school accounts)
    Accounts in any organizational directory ... and personal Microsoft accounts Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts
  5. Leave Redirect URI empty.

  6. Select Register. On the application's Overview page, copy the value of the Application (client) ID and save it. You'll need it in the next step. If you chose Accounts in this organizational directory only for Supported account types, also copy the Directory (tenant) ID and save it.

    A screenshot of the application ID of the new app registration

  7. Select Authentication under Manage. Locate the Advanced settings section and change the Allow public client flows toggle to Yes, then choose Save.

    A screenshot of the Allow public client flows toggle

Note

Notice that you didn't configure any Microsoft Graph permissions on the app registration. The sample uses dynamic consent to request specific permissions for user authentication.

Create a .NET console app

Begin by creating a new .NET console project using the .NET CLI.

  1. Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command.

    dotnet new console -o GraphTutorial
    
  2. 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 dependencies that you use later.

To install dependencies, run the following commands in your CLI.

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

Next, add the details of your app registration to the project.

  1. Create a file in the GraphTutorial directory named appsettings.json and add the following code.

    {
      "settings": {
        "clientId": "YOUR_CLIENT_ID_HERE",
        "tenantId": "common",
        "graphUserScopes": [
          "user.read",
          "mail.read",
          "mail.send"
        ]
      }
    }
    
  2. Update the values according to the following table.

    Setting Value
    clientId The client ID of your app registration
    tenantId If you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as common.

    Tip

    Optionally, you can set these values in a separate file named appsettings.Development.json, or in the .NET Secret Manager.

  3. Update GraphTutorial.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>
    
  4. Create a file in the GraphTutorial directory named Settings.cs and add the following code.

    using Microsoft.Extensions.Configuration;
    
    public class Settings
    {
        public string? ClientId { get; set; }
        public string? TenantId { get; set; }
        public string[]? GraphUserScopes { 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

Continue by creating a simple console-based menu.

  1. Open ./Program.cs and replace its entire contents with the following code.

    Console.WriteLine(".NET Graph Tutorial\n");
    
    var settings = Settings.LoadSettings();
    
    // Initialize Graph
    InitializeGraph(settings);
    
    // Greet the user by name
    await GreetUserAsync();
    
    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 my inbox");
        Console.WriteLine("3. Send mail");
        Console.WriteLine("4. 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 emails from user's inbox
                await ListInboxAsync();
                break;
            case 3:
                // Send an email message
                await SendMailAsync();
                break;
            case 4:
                // Run any Graph code
                await MakeGraphCallAsync();
                break;
            default:
                Console.WriteLine("Invalid choice! Please try again.");
                break;
        }
    }
    
  2. Add the following placeholder methods at the end of the file. You implement them in later steps.

    void InitializeGraph(Settings settings)
    {
        // TODO
    }
    
    async Task GreetUserAsync()
    {
        // TODO
    }
    
    async Task DisplayAccessTokenAsync()
    {
        // TODO
    }
    
    async Task ListInboxAsync()
    {
        // TODO
    }
    
    async Task SendMailAsync()
    {
        // TODO
    }
    
    async Task MakeGraphCallAsync()
    {
        // TODO
    }
    

This implements a basic menu and reads the user's choice from the command line.

Next step