使用msgraph-sdk-go获取用户Drive报401错误的解决咨询
问题场景
使用msgraph-sdk-go官方示例代码调用接口获取用户Drive时,触发401未授权错误,系统提示请求体必须包含client_assertion或client_secret,但示例代码中并无构造该请求体的逻辑,且已完成浏览器端的应用注册认证流程。
失败代码片段
result, err := client.Me().Drive().Get(context.Background(), nil) if err != nil { fmt.Printf("Error getting the drive: %v\n", err) printOdataError(err) } fmt.Printf("Found Drive : %v\n", *result.GetId())
错误详情
Error getting the drive: DeviceCodeCredential authentication failed
POST https://login.microsoftonline.com/efa4b4f3-5e38-4866-9206-79c604d86e7c/oauth2/v2.0/token
RESPONSE 401 Unauthorized
"error": "invalid_client",
"error_description": "AADSTS7000218: The request body must contain the following parameter: 'client_assertion' or 'client_secret'.
Trace ID: b6f28bb4-6bed-4dfe-a275-c0343fb91e01
Correlation ID: c06d2257-b3ab-4df3-ba58-ab271cf97508
Timestamp: 2023-02-14 14:18:22Z"
"error_codes": [ 7000218 ],
"timestamp": "2023-02-14 14:18:22Z",
"trace_id": "b6f28bb4-6bed-4dfe-a275-c0343fb91e01",
"correlation_id": "c06d2257-b3ab-4df3-ba58-ab271cf97508",
"error_uri": "https://login.microsoftonline.com/error?code=7000218"
已完成的前置配置
- 创建移动/桌面类型的Azure AD应用注册,设置重定向URI为
http://localhost - 配置客户端及设备代码凭据,添加
TenantID字段 - 为应用分配了所需的API权限
解决方案
进入Azure AD应用注册的「认证」页面,开启**「允许以下移动和桌面流」**选项,重新执行代码即可解决该错误。
内容的提问来源于stack exchange,提问作者Dean Schulze

