How to get Azure AD JWT in GO

huangapple go评论71阅读模式
英文:

How to get Azure AD JWT in GO

问题

所以我正在尝试使用Go语言。我需要手动调用一个受Azure AD保护的端点的REST调用。我正在使用Azure Identity包,但是我仍然无法获得令牌。

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("没有错误 😊")
	var ctx = context.TODO()
	fmt.Println(cred.GetToken(ctx))
}

然后会出现以下错误响应:

# command-line-arguments
.\main.go:19:27: 转换为context.Context缺少参数: context.Context()

有人可以指点我做错了什么吗?

英文:

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?

答案1

得分: 1

context.Context 是一个接口,而不是一个方法(https://pkg.go.dev/context#Context),这就是为什么你会得到这个错误,你试图将空值转换为该类型。

对 GetToken 方法的调用需要一个实现了 context.Context 的对象。

尝试将 var ctx = context.Context() 替换为 var ctx = context.Background()

在这里阅读更多关于 context.Context 的信息:https://pkg.go.dev/context

英文:

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

huangapple
  • 本文由 发表于 2022年2月23日 08:53:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/71230125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定