【问题标题】:Gmail API - Oauth2/google: no credentials found (Golang)Gmail API - Oauth2/google:找不到凭据(Golang)
【发布时间】:2021-10-02 04:02:04
【问题描述】:

​大家好, 想要为 Gmail API 做服务器端集成。基本需求是使用启用 Gmail API 我想读取我的 Gmail 收件箱以进行某些分析。

Golang 包 - “google.golang.org/api/gmail/v1”

根据文档,我已按照以下步骤操作。

  1. 新注册的 Gmail

  2. 添加了使用 GCP 服务的结算明细

  3. 创建测试项目

  4. 启用 Gmail API

  5. 在其中创建了服务帐户和密钥。得到了 credentials.json 文件

  6. 在后端,我使用 Golang 包来提取 Gmail 收件箱。

  7. 成功集成后,我试图运行我的代码,但得到 以下错误

    {"level":"error","msg":"Error while creating gmail service : oauth2/google: no credentials found","time":"2021-07-25T15:11:23+05:30"}    

谁能帮我弄清楚缺少什么?

【问题讨论】:

  • 在您的问题中输入您尝试运行的代码
  • 要重现这一点,我需要注册 GCP,创建一个服务帐户,安装“golang 包”,不管是什么,并编写具有相同错误的代码。这超出了 Stack Overflow 的范围,所以我会投票关闭,唯一的问题是几个适用的关闭原因中的哪一个。
  • 有多种方法可以验证您的客户端以访问 api。您需要添加与您选择的方法相关的代码。并相应地更新其他因素,以便可以对其进行调试。正如@amt 提到的,无法继续处理这些信息。
  • 在此处添加您正在使用的代码。见minimal-reproducible-example

标签: go google-cloud-platform imap gmail-api service-accounts


【解决方案1】:

我目前将 OAuth 与 YouTube 和设备流程 [1] 一起使用,所以这可能会有所帮助。首先,您需要像这样发出一次性请求:

data := url.Values{
   "client_id": {"something.apps.googleusercontent.com"},
   "scope": {"https://www.googleapis.com/auth/youtube"},
}
res, err := http.PostForm("https://oauth2.googleapis.com/device/code", data)

你会得到这样的回应:

type OAuth struct {
   Device_Code string
   User_Code string
   Verification_URL string
}

您可以像这样对用户进行一次性提示:

1. Go to
https://www.google.com/device

2. Enter this code
HNDN-ZWBL

3. Sign in to your Google Account

然后,在用户登录后,您可以像这样进行交换请求:

data := url.Values{
   "client_id": {"something.apps.googleusercontent.com"},
   "client_secret": {"super secret"},
   "device_code": {"device code from above"},
   "grant_type":  {"urn:ietf:params:oauth:grant-type:device_code"},
}
res, err := http.PostForm("https://oauth2.googleapis.com/token", data)

这将为您提供access_tokenrefresh_token,您可以将其保存在本地以供重复使用。除了“设备流”,还有“原生应用”流[2],但我发现前者是一个更简单的过程。

  1. https://developers.google.com/identity/sign-in/devices
  2. https://developers.google.com/identity/protocols/oauth2/native-app

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 2012-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2015-06-19
    • 1970-01-01
    • 2021-12-14
    • 2015-06-03
    相关资源
    最近更新 更多