title | description | author | ms.author | ms.topic | date |
---|---|---|---|---|---|
Build API clients for .NET with Microsoft identity authentication |
Learn how use Kiota to build API clients in .NET to access APIs that require Microsoft identity authentication. |
jasonjoh |
jasonjoh |
tutorial |
11/29/2023 |
In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.
Run the following command in the directory you want to create a new project.
dotnet new console -o GetUserClient
dotnet new gitignore
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. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.
- Authentication (Kiota default Azure authentication)
- HTTP (Kiota default HttpClient-based implementation)
- Form serialization (Kiota default)
- JSON serialization (Kiota default)
- Text serialization (Kiota default)
- Multipart serialization (Kiota default)
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.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
Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.
:::code language="yaml" source="~/code-snippets/get-started/azure-auth/get-me.yml":::
You can then use the Kiota command line tool to generate the API client classes.
kiota generate -l csharp -d get-me.yml -c GetUserApiClient -n GetUserClient.ApiClient -o ./Client
[!INCLUDE register-azure-app-device-code-intro]
[!INCLUDE register-azure-app-device-code-portal]
[!INCLUDE register-azure-app-device-code-powershell]
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.
:::code language="csharp" source="~/code-snippets/get-started/azure-auth/dotnet/src/Program.cs" id="ProgramSnippet":::
Note
This example uses the DeviceCodeCredential
class. You can use any of the credential classes from the Azure.Identity
library.
To start the application, run the following command in your project directory.
dotnet run
- kiota-samples repository contains the code from this guide.
- ToDoItem Sample API implements a sample OpenAPI in ASP.NET Core and sample clients in multiple languages.