Skip to content

Instantly share code, notes, and snippets.

@maisarissi
Created May 2, 2023 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maisarissi/639d9ac7a1b0993c176672d2cceb0e91 to your computer and use it in GitHub Desktop.
Save maisarissi/639d9ac7a1b0993c176672d2cceb0e91 to your computer and use it in GitHub Desktop.
microsoftgraph-go-v1-devicecodeflow
import (
    "context"
    "fmt"
    "log"
    "os"
    "strings"
    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    auth "github.com/microsoft/kiota-authentication-azure-go"
    msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go"
)
type GraphHelper struct {
    deviceCodeCredential *azidentity.DeviceCodeCredential
    client           *msgraphsdk.GraphServiceClient
    graphUserScopes      []string
}
func (g *GraphHelper) InitializeGraphUsingDeviceCodeFlow() error {
    clientId := os.Getenv("CLIENT_ID")
    tenantId := os.Getenv("TENANT_ID")
    scopes := os.Getenv("GRAPH_USER_SCOPES")
    g.graphUserScopes = strings.Split(scopes, ",")
    // Create the device code credential
    credential, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
        ClientID: clientId,
        TenantID: tenantId,
        UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
            fmt.Println(message.Message)
            return nil
        },
    })
    if err != nil {
        return err
    }
    g.deviceCodeCredential = credential
    // Create an auth provider using the credential
    authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(credential, g.graphUserScopes)
    if err != nil {
        return err
    }
    adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider)
    if err != nil {
        return err
    }
    // Create a client
    userClient := msgraphsdk.NewGraphServiceClient(adapter)
    g.client = userClient
    return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment