Skip to content

Instantly share code, notes, and snippets.

@antonxo
Created January 11, 2024 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonxo/6a53de56e99111e505310326f79bb506 to your computer and use it in GitHub Desktop.
Save antonxo/6a53de56e99111e505310326f79bb506 to your computer and use it in GitHub Desktop.
Verify Google Sign-in token in Golang
package main
import (
"context"
"fmt"
"google.golang.org/api/idtoken"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/tokenSignIn", handleTokenSignIn)
fmt.Println("Server started at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
func handleMain(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
}
// Verify Google ID token: https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
func handleTokenSignIn(_ http.ResponseWriter, r *http.Request) {
// parse POST form
if err := r.ParseForm(); err != nil {
log.Fatalln(err)
}
// verify CSRF tokens
const csrfCookieKey = "g_csrf_token"
cookieToken, err := r.Cookie(csrfCookieKey)
if err != nil {
log.Fatalf("failed to retrieve %s from cookie: %s", csrfCookieKey, err)
}
formCookie := r.PostForm.Get(csrfCookieKey)
if formCookie == "" {
log.Fatalf("no %s in POST form", csrfCookieKey)
}
if cookieToken.Value != formCookie {
log.Fatalln("failed to verify double submit cookie")
}
// validate Google token using their library
payload, err := idtoken.Validate(context.Background(), r.PostForm.Get("credential"), googleClientId)
if err != nil {
log.Fatalln(err)
}
fmt.Print(payload.Claims)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment