How to get Azure AD JWT in GO

Issue

So I’m testing the waters with Go. I need to manually make a REST call to an Azure AD protected endpoint. I’m using the Azure Identity package, but still I am not able to get the token.

package main

import (
    "context"
    "fmt"

    azi "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {

    cred, err := azi.NewInteractiveBrowserCredential(nil)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Println("No error 😎")
    var ctx = context.Context()
    fmt.Println(cred.GetToken(ctx))
}

This then yields the following error response

# command-line-arguments
.\main.go:19:27: missing argument to conversion to context.Context: context.Context()

Can someone please point me in the right direction of what I am doing wrong?

Solution

context.Context is an interface, not a method (https://pkg.go.dev/context#Context) that is why you’re getting the error, you’re attempting to convert nothing to that type.

Calls to the GetToken method require something that implements context.Context.

Try replacing var ctx = context.Context() with var ctx = context.Background()

Read more about context.Context here https://pkg.go.dev/context

Answered By – sbrichards

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.