go - 从访问 token 获取 Google 登录个人资料信息 - Golang

标签 go google-signin

我有以下 JavaScript 代码

auth2.grantOfflineAccess().then(function(codeData) {
    if (!codeData) {
        alert("Something went wrong");
        return;
    }

    $.post("/do/signIn/google", codeData, function() { ... });
});

我正在将 Google 登录代码发送到我的 golang 网络应用程序。 我从 POST https://www.googleapis.com/oauth2/v4/token 成功获得了访问 token 。

我的问题是,我无法获取用户的个人资料信息(例如电子邮件、显示名称等)

我尝试发送请求到 GET https://www.googleapis.com/auth/userinfo.profile?access_token=xxx,但我收到了一个空响应(空白正文)。

最佳答案

您必须对 POST https://www.googleapis.com/oauth2/v4/token 返回的 Google ID token 进行解码,以将其转换为 Google+ ID,然后您可以使用 GET https://www.googleapis.com/plus/v1/people/[gplusID]?access_token=[accessToken]

Using Go, you can decode the google ID token using the following function. Normally, it is critical that you validate an ID token before you use it, but since you are communicating directly with Google over an intermediary-free HTTPS channel and using your Client Secret to authenticate yourself to Google, you can be confident that the token you receive really comes from Google and is valid. If your server passes the ID token to other components of your app, it is extremely important that the other components validate the token before using it.

使用 Go,您可以使用以下函数解码 ID token 。

func decodeGoogleIDToken(idToken string) (gplusID string, err error) {
    var set struct {
        Sub string
    }
    if idToken != "" {
        // Check that the padding is correct for a base64decode
        parts := strings.Split(idToken, ".")
        if len(parts) < 2 {
            return "", fmt.Errorf("Malformed ID token")
        }
        // Decode the ID token
        s := parts[1]
        switch len(s) % 4 {
        case 2:
            s += "=="
        case 3:
            s += "="
        }

        b, err := base64.URLEncoding.DecodeString(s)
        if err != nil {
            return "", fmt.Errorf("Malformed ID token: %v", err)
        }
        err = json.Unmarshal(b, &set)
        if err != nil {
            return "", fmt.Errorf("Malformed ID token: %v", err)
        }
    }
    return set.Sub, nil
}

在此处查看示例 https://play.golang.org/p/M7sYmE2ztx

关于go - 从访问 token 获取 Google 登录个人资料信息 - Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339163/

相关文章:

json - 如何在 golang 中解析 JSON?

go - 无法将结构类型参数传递给另一个包中的函数

go - LinkedIn Vector Asset API 不断返回 400 Bad Request

android - 如何解决在 Play 商店发布应用后无法正常工作的 Android 谷歌签名问题?

android - Firebase 身份验证 : Android: Unable to display user email and photo

java - android - 如何访问抽屉导航标题项?

Golang 中的 Json 解码/解码

arrays - 将int映射到2D数组

javascript - 授予脱机访问帐户选择器不尊重托管域

ios - 无法在 iOS 模拟器上通过 Google 登录