登录
首页 >  Golang >  Go问答

在 Docker 容器中无法通过 Google API 获取 AccessToken

来源:stackoverflow

时间:2024-03-24 22:51:46 295浏览 收藏

在 Docker 容器中部署网络应用程序时,使用 Google API 获取 AccessToken 出现错误。原因是默认的 Alpine 镜像缺乏证书,导致无法调用 HTTPS 地址。解决方法是在 Dockerfile 中安装 openssl 和 ca-certificates 软件包,并添加 Google 颁发的 CA 证书到受信任证书存储区。

问题内容

我有一个用go编写的网络应用程序,使用oauth2(包golang.org/x/oauth2)通过google登录用户(按照本教程https://developers.google.com/identity/sign-in/网络/服务器端流)。

当我在本地测试应用程序时,它工作正常,但是当我部署应用程序并在 docker 容器内运行时(基于 alpine:latest,运行二进制文件),它出现错误: post https://accounts.google.com/o/oauth2/token:x509:由未知机构签名的证书

这是我交换 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
}

解决方案


问题不是 go 造成的,而是 alpine 镜像造成的。

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

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

apk add --no-cache ca-certificates openssl

您需要将 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

终于介绍完啦!小伙伴们,这篇关于《在 Docker 容器中无法通过 Google API 获取 AccessToken》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>