Build Go apps with Microsoft Graph and app-only authentication
This tutorial teaches you how to build a Go console app that uses the Microsoft Graph API to access data using app-only authentication. App-only authentication is a good choice for background services or applications that need to access data for all users in an organization.
Note
To learn how to use Microsoft Graph to access data on behalf of a user, see this user (delegated) authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can 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 the Global administrator role. 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 1-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 may work with other versions, but that has not been tested.
Register the app in the portal
In this exercise you will register a new application in Azure Active Directory to enable app-only authentication. You can register an application using the Microsoft Entra admin center, or by using the Microsoft Graph PowerShell SDK.
Register application for app-only authentication
In this section you will register an application that supports app-only authentication using client credentials flow.
Open a browser and navigate to the Microsoft Entra admin center and login 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 App-Only Auth Tutorial
.Set Supported account types to Accounts in this organizational directory only.
Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them, you will need these values in the next step.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.
Select Certificates and secrets under Manage, then select New client secret.
Enter a description, choose a duration, and select Add.
Copy the secret from the Value column, you will need it in the next steps.
Important
This client secret is never shown again, so make sure you copy it now.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. This is because app-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
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 graphapponlytutorial
Install dependencies
Before moving on, add some additional dependencies that you will 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.
Run the following commands in your CLI to install the dependencies.
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
In this section you'll 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 CLIENT_SECRET=YOUR_CLIENT_SECRET_HERE TENANT_ID=YOUR_TENANT_ID_HERE
Update the values according to the following table.
Setting Value CLIENT_ID
The client ID of your app registration CLIENT_SECRET
The client secret of your app registration TENANT_ID
The tenant ID of your organization Tip
Optionally, you can set these values in a separate file named .env.local.
Design the app
In this section you will create 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" "os" "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 { clientSecretCredential *azidentity.ClientSecretCredential appClient *msgraphsdk.GraphServiceClient } func NewGraphHelper() *GraphHelper { g := &GraphHelper{} return g }
This creates a basic GraphHelper type that you will extend in later sections to use Microsoft Graph.
Create a file in the same directory as go.mod named graphapponlytutorial.go. Add the following code.
package main import ( "fmt" "graphapponlytutorial/graphhelper" "log" "github.com/joho/godotenv" ) func main() { fmt.Println("Go Graph App-Only 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) 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 users") fmt.Println("3. 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 users listUsers(graphHelper) case 3: // 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'll implement them in later steps.
func initializeGraph(graphHelper *graphhelper.GraphHelper) { // TODO } func displayAccessToken(graphHelper *graphhelper.GraphHelper) { // TODO } func listUsers(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.
Add app-only authentication
In this section you will add app-only authentication to the application. his is required to obtain the necessary OAuth access token to call the Microsoft Graph. In this step you will integrate the Azure Identity Client Module for Go into the application and configure authentication for the Microsoft Graph SDK for Go.
The Azure Identity library provides a number of TokenCredential
classes that implement OAuth2 token flows. The Microsoft Graph SDK uses those classes to authenticate calls to Microsoft Graph.
Configure Graph client for app-only authentication
In this section you will use the ClientSecretCredential
class to request an access token by using the client credentials flow.
Add the following function to ./graphhelper/graphhelper.go.
func (g *GraphHelper) InitializeGraphForAppAuth() error { clientId := os.Getenv("CLIENT_ID") tenantId := os.Getenv("TENANT_ID") clientSecret := os.Getenv("CLIENT_SECRET") credential, err := azidentity.NewClientSecretCredential(tenantId, clientId, clientSecret, nil) if err != nil { return err } g.clientSecretCredential = credential // Create an auth provider using the credential authProvider, err := auth.NewAzureIdentityAuthenticationProviderWithScopes(g.clientSecretCredential, []string{ "https://graph.microsoft.com/.default", }) if err != nil { return err } // Create a request adapter using the auth provider adapter, err := msgraphsdk.NewGraphRequestAdapter(authProvider) if err != nil { return err } // Create a Graph client using request adapter client := msgraphsdk.NewGraphServiceClient(adapter) g.appClient = client return nil }
Tip
If you are using goimports, some modules may have been auto-removed from your
import
statement in graphhelper.go on save. You may need to re-add the modules to build.Replace the empty
initializeGraph
function in graphapponlytutorial.go with the following.func initializeGraph(graphHelper *graphhelper.GraphHelper) { err := graphHelper.InitializeGraphForAppAuth() if err != nil { log.Panicf("Error initializing Graph for app auth: %v\n", err) } }
This code initializes two properties, a DeviceCodeCredential
object and a GraphServiceClient
object. The InitializeGraphForUserAuth
function creates a new instance of DeviceCodeCredential
, then uses that instance to create a new instance of GraphServiceClient
. Every time an API call is made to Microsoft Graph through the userClient
, it will use the provided credential to get an access token.
Test the ClientSecretCredential
Next, add code to get an access token from the ClientSecretCredential
.
Add the following function to ./graphhelper/graphhelper.go.
func (g *GraphHelper) GetAppToken() (*string, error) { token, err := g.clientSecretCredential.GetToken(context.Background(), policy.TokenRequestOptions{ Scopes: []string{ "https://graph.microsoft.com/.default", }, }) if err != nil { return nil, err } return &token.Token, nil }
Replace the empty
displayAccessToken
function in graphapponlytutorial.go with the following.func displayAccessToken(graphHelper *graphhelper.GraphHelper) { token, err := graphHelper.GetAppToken() if err != nil { log.Panicf("Error getting user token: %v\n", err) } fmt.Printf("App-only token: %s", *token) fmt.Println() }
Build and run the app by running
go run graphapponlytutorial
. Enter1
when prompted for an option. The application displays an access token.Go Graph App-Only Tutorial Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 1 App-only token: eyJ0eXAiOiJKV1QiLCJub25jZSI6IlVDTzRYOWtKYlNLVjVkRzJGenJqd2xvVUcwWS...
Tip
For validation and debugging purposes only, you can decode app-only access tokens using Microsoft's online token parser at https://jwt.ms. This can be useful if you encounter token errors when calling Microsoft Graph. For example, verifying that the
role
claim in the token contains the expected Microsoft Graph permission scopes.
List users
In this section you will add the ability to list all users in your Azure Active Directory using app-only authentication.
Add the following function to ./graphhelper/graphhelper.go.
func (g *GraphHelper) GetUsers() (models.UserCollectionResponseable, error) { var topValue int32 = 25 query := users.UsersRequestBuilderGetQueryParameters{ // Only request specific properties Select: []string{"displayName", "id", "mail"}, // Get at most 25 results Top: &topValue, // Sort by display name Orderby: []string{"displayName"}, } return g.appClient.Users(). Get(context.Background(), &users.UsersRequestBuilderGetRequestConfiguration{ QueryParameters: &query, }) }
Replace the empty
listUsers
function in graphapponlytutorial.go with the following.func listUsers(graphHelper *graphhelper.GraphHelper) { users, err := graphHelper.GetUsers() if err != nil { log.Panicf("Error getting users: %v", err) } // Output each user's details for _, user := range users.GetValue() { fmt.Printf("User: %s\n", *user.GetDisplayName()) fmt.Printf(" ID: %s\n", *user.GetId()) noEmail := "NO EMAIL" email := user.GetMail() if email == nil { email = &noEmail } fmt.Printf(" Email: %s\n", *email) } // If GetOdataNextLink does not return nil, // there are more users available on the server nextLink := users.GetOdataNextLink() fmt.Println() fmt.Printf("More users available? %t\n", nextLink != nil) fmt.Println() }
Run the app, sign in, and choose option 2 to list users.
Please choose one of the following options: 0. Exit 1. Display access token 2. List users 3. Make a Graph call 2 User: Adele Vance ID: 05fb57bf-2653-4396-846d-2f210a91d9cf Email: AdeleV@contoso.com User: Alex Wilber ID: a36fe267-a437-4d24-b39e-7344774d606c Email: AlexW@contoso.com User: Allan Deyoung ID: 54cebbaa-2c56-47ec-b878-c8ff309746b0 Email: AllanD@contoso.com User: Bianca Pisani ID: 9a7dcbd0-72f0-48a9-a9fa-03cd46641d49 Email: NO EMAIL User: Brian Johnson (TAILSPIN) ID: a8989e40-be57-4c2e-bf0b-7cdc471e9cc4 Email: BrianJ@contoso.com ... More users available? true
Code explained
Consider the code in the GetUsers
function.
- It gets a collection of users
- It uses
Select
to request specific properties - It uses
Top
to limit the number of users returned - It uses
OrderBy
to sort the response
Optional: add your own code
In this section you will add your own Microsoft Graph capabilities to the application. This could be a code snippet from Microsoft Graph documentation or Graph Explorer, or code that you created. This section is optional.
Update the app
Add the following function to ./graphhelper/graphhelper.go.
func (g *GraphHelper) MakeGraphCall() error { // INSERT YOUR CODE HERE return nil }
Replace the empty
makeGraphCall
function in graphapponlytutorial.go with the following.func makeGraphCall(graphHelper *graphhelper.GraphHelper) { err := graphHelper.MakeGraphCall() if err != nil { log.Panicf("Error making Graph call: %v", err) } }
Choose an API
Find an API in Microsoft Graph you'd like to try. For example, the Create event API. You can use one of the examples in the API documentation, or you can customize an API request in Graph Explorer and use the generated snippet.
Configure permissions
Check the Permissions section of the reference documentation for your chosen API to see which authentication methods are supported. Some APIs don't support app-only, or personal Microsoft accounts, for example.
- To call an API with user authentication (if the API supports user (delegated) authentication), see the user (delegated) authentication tutorial.
- To call an API with app-only authentication (if the API supports it), add the required permission scope in the Azure AD admin center.
Add your code
Copy your code into the MakeGraphCall
function in graphhelper.go. If you're copying a snippet from documentation or Graph Explorer, be sure to rename the GraphServiceClient
to appClient
.
Congratulations!
You've completed the Go Microsoft Graph tutorial. Now that you have a working app that calls Microsoft Graph, you can experiment and add new features.
- Learn how to use user (delegated) authentication with the Microsoft Graph Go SDK.
- Visit the Overview of Microsoft Graph to see all of the data you can access with Microsoft Graph.
Have an issue with this section? If so, please give us some feedback so we can improve this section.