Validating Google sign in ID token in Go

为君一笑 提交于 2019-12-05 12:00:31

This is how I've done it using https://github.com/google/google-api-go-client library:

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 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.

Google's idToken is actually in JWT format, which is compact and self-contained JSON with signature.

See also: https://jwt.io/introduction/

google-auth-library-nodejs's OAuth2Client.prototype.verifyIdToken verify the idtoken using Google's public key and extract ClaimSet from the idtoken without calling the tokeninfo endpoint.

I just ported the verifyIdToken function from google-auth-library-nodejs, and created a library for this: https://github.com/futurenda/google-auth-id-token-verifier.

Usage:

import (
     "github.com/futurenda/google-auth-id-token-verifier"
)

v := googleAuthIDTokenVerifier.Verifier{}
aud := "xxxxxx-yyyyyyy.apps.googleusercontent.com"
err := v.VerifyIDToken(TOKEN, []string{
    aud,
})
if err == nil {
    claimSet, err := googleAuthIDTokenVerifier.Decode(TOKEN)
    // claimSet.Iss,claimSet.Email ... (See claimset.go)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!