Upravit

Sdílet prostřednictvím


Build API clients for Go with Azure authentication

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

Required tools

Create a project

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

go mod init getuser

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 bundle package. For more information about Kiota dependencies, see the dependencies documentation.

Run the following commands to get the required dependencies.

go get github.com/microsoft/kiota-bundle-go
go get github.com/microsoft/kiota-authentication-azure-go
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

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 -l go -d ../get-me.yml -c GraphApiClient -n getuser/client -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

Create a file in the root of the project named getuser.go and add the following code. Replace YOUR_CLIENT_ID with the client ID from your app registration.

package main

import (
    "context"
    "fmt"

    "getuser/client"

    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    azure "github.com/microsoft/kiota-authentication-azure-go"
    bundle "github.com/microsoft/kiota-bundle-go"
)

func main() {
    clientId := "YOUR_CLIENT_ID"

    // The auth provider will only authorize requests to
    // the allowed hosts, in this case Microsoft Graph
    allowedHosts := []string{"graph.microsoft.com"}
    graphScopes := []string{"User.Read"}

    credential, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
        ClientID: clientId,
        UserPrompt: func(ctx context.Context, dcm azidentity.DeviceCodeMessage) error {
            fmt.Println(dcm.Message)
            return nil
        },
    })

    if err != nil {
        fmt.Printf("Error creating credential: %v\n", err)
    }

    authProvider, err := azure.NewAzureIdentityAuthenticationProviderWithScopesAndValidHosts(
        credential, graphScopes, allowedHosts)

    if err != nil {
        fmt.Printf("Error creating auth provider: %v\n", err)
    }

    adapter, err := bundle.NewDefaultRequestAdapter(authProvider)

    if err != nil {
        fmt.Printf("Error creating request adapter: %v\n", err)
    }

    client := client.NewGraphApiClient(adapter)

    me, err := client.Me().Get(context.Background(), nil)

    if err != nil {
        fmt.Printf("Error getting user: %v\n", err)
    }

    fmt.Printf("Hello %s, your ID is %s\n", *me.GetDisplayName(), *me.GetId())
}

Note

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

Run the application

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

go run .

See also