如何使用oauth2令牌在MS Graph SDK中进行身份验证?

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

How to authenticate in MS Graph SDK with oauth2 token?

问题

我使用常规的工作流程通过golang.org/x/oauth2获取了oauth2令牌,但无法对graph sdk (github.com/microsoftgraph/msgraph-sdk-go)进行身份验证。我的应用程序允许多租户AD和个人帐户。

我实现了azcore.TokenCredential接口:

type azureTokenCredential struct {
	token oauth2.Token
}

func (c azureTokenCredential) GetToken(_ context.Context, _ policy.TokenRequestOptions) (*azcore.AccessToken, error) {
	return &azcore.AccessToken{
		Token:     c.token.AccessToken,
		ExpiresOn: c.token.Expiry,
	}, nil
}

这是我如何使用它的方式:

cred := azureTokenCredential{token: token}
auth, err := a.NewAzureIdentityAuthenticationProvider(cred)
if err != nil {
	return "", errors.WithStack(err)
}
adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
if err != nil {
	return "", errors.WithStack(err)
}
client := msgraphsdk.NewGraphServiceClient(adapter)
u, err := client.Me().Get(nil)

当我使用AD帐户登录时,我收到以下错误消息:

服务器返回了意外的状态代码,并且没有为此代码注册错误工厂:401

英文:

I acquired the oauth2 token using the usual workflow via golang.org/x/oauth2 but can't authenticate graph sdk (github.com/microsoftgraph/msgraph-sdk-go). My app allows both multi-tenant AD and personal accounts.

I implemented azcore.TokenCredential interface:

type azureTokenCredential struct {
	token oauth2.Token
}

func (c azureTokenCredential) GetToken(_ context.Context, _ policy.TokenRequestOptions) (*azcore.AccessToken, error) {
	return &azcore.AccessToken{
		Token:     c.token.AccessToken,
		ExpiresOn: c.token.Expiry,
	}, nil
}

And that's how I use it:

cred := azureTokenCredential{token: token}
auth, err := a.NewAzureIdentityAuthenticationProvider(cred)
if err != nil {
	return "", errors.WithStack(err)
}
adapter, err := msgraphsdk.NewGraphRequestAdapter(auth)
if err != nil {
	return "", errors.WithStack(err)
}
client := msgraphsdk.NewGraphServiceClient(adapter)
u, err := client.Me().Get(nil)

I get the following error when I sign in with an AD account:

> The server returned an unexpected status code and no error factory is registered for this code: 401

答案1

得分: 0

通过将oauth2配置中的范围更改为https://graph.microsoft.com/.default来修复。现在,当用户登录时,会看到一个同意屏幕。我还从我的应用注册页面的API权限屏幕中添加了必要的Microsoft Graph权限。

英文:

Fixed by changing the scope in the oauth2 config to https://graph.microsoft.com/.default. Now when a user signs in it sees a consent screen. I also added necessary Microsoft Graph permissions from the API permissions screen of my App Registration page.

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

发表评论

匿名网友

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

确定