英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论