无法从 Google API 和 Docker 容器交换访问令牌

Cannot exchange AccessToken from Google API inside Docker container

我有一个用 Go 编写的网络应用程序,使用 oauth2(包 golang.org/x/oauth2)通过 Google 登录用户(按照本教程 https://developers.google.com/identity/sign-in/web/server-side-flow)。

当我在本地测试应用程序时,它工作正常但是当我在 Docker 容器中部署应用程序和 运行 时(基于 alpine:latest、运行 二进制文件),它有一个错误: Post https://accounts.google.com/o/oauth2/token: x509: certificate signed by unknown authority

这是我交换 accessToken 的代码:

ctx = context.Background()

config := &oauth2.Config{
    ClientID:     config.GoogleClientId,
    ClientSecret: config.GoogleClientSecret,
    RedirectURL:  config.GoogleLoginRedirectUrl,
    Endpoint:     google.Endpoint,
    Scopes:       []string{"email", "profile"},
}

accessToken, err := config.Exchange(ctx, req.Code)
if err != nil {
    log.Println(err.Error())   // Error here
}

您需要将 Google 颁发 CA 证书添加到 docker 映像的受信任证书存储区。

Google CA 证书是 https://pki.google.com/GIAG2.crt .

可以从 here

中找到有关证书的更多信息

然后在 Dockerfile 中,你需要做这样的事情

cp GIAG2.crt /usr/local/share/ca-certificates/GIAG2.crt
update-ca-certificates

不是Go的问题,而是Alpine镜像的问题

默认的 Alpine 图像没有证书,因此应用无法调用 https 地址(本例为 https://accounts.google.com/o/oauth2/token)。

要解决此问题,请安装 2 个软件包 opensslca-certificates。 Dockerfile 中的示例:

apk add --no-cache ca-certificates openssl