用于获取用户驱动器的 msgraph-sdk-go 示例代码失败

分享于2023年03月01日 go microsoft-graph-api 问答
【问题标题】:msgraph-sdk-go example code for getting user's drive fails用于获取用户驱动器的 msgraph-sdk-go 示例代码失败
【发布时间】:2023-02-15 03:23:26
【问题描述】:

msgraph-sdk-go 获取用户驱动器的示例代码失败并出现以下 401 错误。它期望请求主体包含 client_secret,尽管示例代码中没有创建请求主体的位置。

示例代码确实通过网络浏览器成功验证了我注册的应用程序。

使用 msgraph-sdk-go 需要什么?

这是失败的代码:

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'.\r\nTrace ID: b6f28bb4-6bed-4dfe-a275-c0343fb91e01\r\nCorrelation ID: c06d2257-b3ab-4df3-ba58-ab271cf97508\r\nTimestamp: 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"
}


【解决方案1】:

假设您使用设备代码凭据设置您的客户端,并给出您使用类似于此的代码获得的错误消息

cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
    ClientID: "CLIENT_ID",
    UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
        fmt.Println(message.Message)
        return nil
    },
})

client := msgraphsdk.NewGraphServiceClientWithCredentials(cred, []string{"User.Read"})

注册的应用程序需要正确配置以允许设备关闭流程。 为了那个原因:

  1. 转到 the azure portal
  2. 导航到应用程序注册(Azure Active Directory,然后是应用程序注册)。
  3. 在列表中找到您的申请注册。
  4. 单击身份验证选项卡
  5. 确保选中移动和桌面应用程序平台并选中 https://login.microsoftonline.com/common/oauth2/nativeclient URL。
  6. 确保将“启用以下移动和桌面流”设置为“是”。
  7. 单击“保存”。

    几个屏幕截图可以指导您完成。

【讨论】: