Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This tutorial teaches you how to build a Go console app that uses the Microsoft Graph API to access data on behalf of a user.
Note
To learn how to use Microsoft Graph to access data using app-only authentication, see this app-only authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download the completed code through the quick start tool, which automates app registration and configuration. The downloaded code works without any modifications required.
You can also download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have Go installed on your development machine.
You should also have a Microsoft work or school account with an Exchange Online mailbox. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a one-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with Go version 1.19.3. The steps in this guide might work with other versions, but that hasn't been tested.
Register an application for user authentication
Register an application that supports user authentication using device code flow. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Open a browser and navigate to the Microsoft Entra admin center and sign in using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph User Auth Tutorial
.Set Supported account types as desired. The options are:
Option Who can sign in? Accounts in this organizational directory only Only users in your Microsoft 365 organization Accounts in any organizational directory Users in any Microsoft 365 organization (work or school accounts) Accounts in any organizational directory ... and personal Microsoft accounts Users in any Microsoft 365 organization (work or school accounts) and personal Microsoft accounts Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and save it. You'll need it in the next step. If you chose Accounts in this organizational directory only for Supported account types, also copy the Directory (tenant) ID and save it.
Select Authentication under Manage. Locate the Advanced settings section and change the Allow public client flows toggle to Yes, then choose Save.
Note
Notice that you didn't configure any Microsoft Graph permissions on the app registration. The sample uses dynamic consent to request specific permissions for user authentication.
Create a Go console app
Begin by initializing a new Go module using the Go CLI. Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command.
go mod init graphtutorial
Install dependencies
Before moving on, add dependencies that you use later.
- Azure Identity Client Module for Go to authenticate the user and acquire access tokens.
- Microsoft Graph SDK for Go to make calls to the Microsoft Graph.
- GoDotEnv for reading environment variables from .env files.
To install the dependencies, run the following commands in your CLI.
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get github.com/microsoftgraph/msgraph-sdk-go
go get github.com/joho/godotenv
Load application settings
Next, add the details of your app registration to the project.
Create a file in the same directory as go.mod named .env and add the following code.
CLIENT_ID=YOUR_CLIENT_ID_HERE TENANT_ID=common GRAPH_USER_SCOPES=user.read,mail.read,mail.send
Update the values according to the following table.
Setting Value CLIENT_ID
The client ID of your app registration TENANT_ID
If you chose the option to only allow users in your organization to sign in, change this value to your tenant ID. Otherwise leave as common
.Tip
Optionally, you can set these values in a separate file named .env.local.
Design the app
Continue by creating a simple console-based menu.
Create a new directory in the same directory as go.mod named graphhelper.
Add a new file in the graphhelper directory named graphhelper.go and add the following code.
package graphhelper import ( "context" "fmt" "os" "strings" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" auth "github.com/microsoft/kiota-authentication-azure-go" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" "github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/users" ) type GraphHelper struct { deviceCodeCredential *azidentity.DeviceCodeCredential userClient *msgraphsdk.GraphServiceClient graphUserScopes []string } func NewGraphHelper() *GraphHelper { g := &GraphHelper{} return g }
This code creates a basic GraphHelper type that you extend in later sections to use Microsoft Graph.
Create a file in the same directory as go.mod named graphtutorial.go. Add the following code.
package main import ( "fmt" "graphtutorial/graphhelper" "log" "time" "github.com/joho/godotenv" ) func main() { fmt.Println("Go Graph Tutorial") fmt.Println() // Load .env files // .env.local takes precedence (if present) godotenv.Load(".env.local") err := godotenv.Load() if err != nil { log.Fatal("Error loading .env") } graphHelper := graphhelper.NewGraphHelper() initializeGraph(graphHelper) greetUser(graphHelper) var choice int64 = -1 for { fmt.Println("Please choose one of the following options:") fmt.Println("0. Exit") fmt.Println("1. Display access token") fmt.Println("2. List my inbox") fmt.Println("3. Send mail") fmt.Println("4. Make a Graph call") _, err = fmt.Scanf("%d", &choice) if err != nil { choice = -1 } switch choice { case 0: // Exit the program fmt.Println("Goodbye...") case 1: // Display access token displayAccessToken(graphHelper) case 2: // List emails from user's inbox listInbox(graphHelper) case 3: // Send an email message sendMail(graphHelper) case 4: // Run any Graph code makeGraphCall(graphHelper) default: fmt.Println("Invalid choice! Please try again.") } if choice == 0 { break } } }
Add the following placeholder methods at the end of the file. You implement them in later steps.
func initializeGraph(graphHelper *graphhelper.GraphHelper) { // TODO } func greetUser(graphHelper *graphhelper.GraphHelper) { // TODO } func displayAccessToken(graphHelper *graphhelper.GraphHelper) { // TODO } func listInbox(graphHelper *graphhelper.GraphHelper) { // TODO } func sendMail(graphHelper *graphhelper.GraphHelper) { // TODO } func makeGraphCall(graphHelper *graphhelper.GraphHelper) { // TODO }
This implements a basic menu and reads the user's choice from the command line.