如何使用 oauth2 令牌在 MS Graph SDK 中进行身份验证?
我通过 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过将 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.