在 Go 中验证 Google 登录 ID 令牌 [英] Validating Google sign in ID token in Go

查看:33
本文介绍了在 Go 中验证 Google 登录 ID 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用 Go 后端服务器项目验证用于 Android 的 Google 登录的 ID 令牌的方法.

I am finding the way to validate ID token for Google sign-in for Android with a Go backend server project.

在 Go 中使用 Google API 客户端库验证 ID 令牌的等效功能是什么?

What is the equivalent function for validating ID tokens by using a Google API Client Library in Go?

从这个页面上使用 Google API 客户端库部分

From this page on Using a Google API Client Library section

https://developers.google.com/identity/sign-in/android/backend-auth#using-a-google-api-client-library

有 Java 和 Python 示例,还有用于使用适用于 PHP、Node.js 和其他语言的 Google API 客户端库验证 ID 令牌的链接.我检查了我的目标语言;去这里

There are Java and Python examples and there are links for verify ID tokens with the Google API Client Library for PHP, Node.js, and other languages. I checked for my target language; Go here

https://github.com/google/google-api-go-client/blob/master/GettingStarted.md

但是,我发现与 Java 和 Python 示例中验证令牌的功能不同.Go 中有什么函数可以做这样的事情吗?

However, I found not equivalent function for validating token like in Java and Python example. Is there any function in Go for doing such thing?

我不想使用令牌信息端点

I don't want to use token info endpoint

https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123

因为它引入了可能的延迟和网络错误.我希望使用 Google API 客户端库.请指导我应该去哪里查看.

since it introduces possible latency and network error. I wish to use Google API Client Library. Please guide me where should I look into.

推荐答案

这就是我使用 https://github.com/google/google-api-go-client 库:

import (
    "google.golang.org/api/oauth2/v2"
    "net/http"
)

var httpClient = &http.Client{}

func verifyIdToken(idToken string) (*oauth2.Tokeninfo, error) {
    oauth2Service, err := oauth2.New(httpClient)
    tokenInfoCall := oauth2Service.Tokeninfo()
    tokenInfoCall.IdToken(idToken)
    tokenInfo, err := tokenInfoCall.Do()
    if err != nil {
        return nil, err
    }
    return tokenInfo, nil
}

oauth2.Tokeninfo 对象包含有关用户的信息.请注意,这会调用 https://www.googleapis.com/oauth2/v2/tokeninfo 并且我认为所有 Google API 客户端库都会在幕后进行此 http 调用.

oauth2.Tokeninfo object has info about the user. Note that this makes a call to https://www.googleapis.com/oauth2/v2/tokeninfo and I think that all Google API Client Libraries make this http call under the hood.

这篇关于在 Go 中验证 Google 登录 ID 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆