Build API clients for a command line interface (CLI) with Microsoft identity authentication

In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.

Required tools

A command line tool is required. We recommend:

Create a project

Run the following command in the directory you want to create a new project.

dotnet new console -o GetUserClient
dotnet new gitignore

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the abstraction package and the cli-commons package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

dotnet add package Microsoft.Kiota.Abstractions
dotnet add package Microsoft.Kiota.Cli.Commons --prerelease
dotnet add package Microsoft.Kiota.Http.HttpClientLibrary
dotnet add package Microsoft.Kiota.Serialization.Form
dotnet add package Microsoft.Kiota.Serialization.Json
dotnet add package Microsoft.Kiota.Serialization.Text
dotnet add package Microsoft.Kiota.Serialization.Multipart
dotnet add package Microsoft.Kiota.Authentication.Azure
dotnet add package Azure.Identity
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package Microsoft.Extensions.Hosting

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the API client classes.

kiota generate --openapi get-me.yml --language CLI -c GetUserApiClient -n GetUserClient.ApiClient -o ./Client

Register an application

To be able to authenticate with the Microsoft identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Azure Active Directory admin center.

The following instructions register an app and enable device code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Leave Redirect URI blank.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Authentication under Manage.

  6. Locate the Advanced settings section. Set the Allow public client flows toggle to Yes, then select Save.

Create the client application

The final step is to update the Program.cs file that was generated as part of the console application to include the following code. Replace YOUR_CLIENT_ID with the client ID from your app registration.

using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using Azure.Identity;
using GetUserClient.ApiClient;
using Microsoft.Kiota.Authentication.Azure;
using Microsoft.Kiota.Cli.Commons.Extensions;
using Microsoft.Kiota.Http.HttpClientLibrary;

var rootCommand = new GetUserApiClient().BuildRootCommand();
rootCommand.Description = "CLI description";

// Set up services
var builder = new CommandLineBuilder(rootCommand)
    .UseDefaults()
    .UseRequestAdapter(ic =>
    {
        // The auth provider will only authorize requests to
        // the allowed hosts, in this case Microsoft Graph
        var allowedHosts = new [] { "graph.microsoft.com" };
        var graphScopes = new [] { "User.Read" };
        var options = new DeviceCodeCredentialOptions
        {
            ClientId = "YOUR_CLIENT_ID",
            DeviceCodeCallback = (code, cancellation) =>
            {
                Console.WriteLine(code.Message);
                return Task.FromResult(0);
            },
        };
        var credential = new DeviceCodeCredential(options);

        var authProvider = new AzureIdentityAuthenticationProvider(credential, allowedHosts, scopes: graphScopes);
        var adapter = new HttpClientRequestAdapter(authProvider);
        adapter.BaseUrl = "https://graph.microsoft.com/v1.0";
        return adapter;
    }).RegisterCommonServices();

return await builder.Build().InvokeAsync(args);

Note

This example uses the DeviceCodeCredential class. You can use any of the credential classes from the Azure.Identity library.

Run the application

To start the application, run the following command in your project directory.

dotnet run -- me get

See also