Created
May 2, 2023 20:30
-
-
Save maisarissi/639d9ac7a1b0993c176672d2cceb0e91 to your computer and use it in GitHub Desktop.
microsoftgraph-go-v1-devicecodeflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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