Skip to content

Instantly share code, notes, and snippets.

@jabgibson
Last active August 29, 2015 14:26
Show Gist options
  • Save jabgibson/d2094c2dd574503608cb to your computer and use it in GitHub Desktop.
Save jabgibson/d2094c2dd574503608cb to your computer and use it in GitHub Desktop.
Google api token checker
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"net/http"
"strings"
)
const (
GOOGLE_TOKEN_URL = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}"
)
func init() {
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/authUser", AuthHandler)
http.Handle("/", r)
http.ListenAndServe(":8443", nil)
}
func AuthHandler(w http.ResponseWriter, r *http.Request) {
x, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Println(err)
}
users_name := validateToken(string(x))
if users_name == "" {
//log that token was invalid
}
// in case of CORS issues.
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write([]byte(users_name))
}
func validateToken(token string) (name string) {
token = strings.Replace(token, "idtoken=", "", 1)
reqPath := strings.Replace(GOOGLE_TOKEN_URL, "{0}", token, 1)
res, err := http.Get(reqPath)
if err != nil {
fmt.Println(err)
}
if res.StatusCode == http.StatusOK {
x, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
}
tokenResponse := TokenResponse{}
err = json.Unmarshal(x, &tokenResponse)
if err != nil {
fmt.Println(err)
}
fmt.Println(tokenResponse)
name = tokenResponse.Name
}
return
}
package main
type TokenResponse struct {
Iss string `json:"iss"`
Sub string `json:"sub"`
Azp string `json:"azp"`
Email string `json:"email"`
AtHash string `json:"at_hash"`
EmailVerified string `json:"email_verified"`
Aud string `json:"aud"`
Iat string `json:"iat"`
Exp string `json:"exp"`
Name string `json:"name"`
Picture string `json:"picture"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Locale string `json:"locale"`
Alg string `json:"alg"`
Kid string `json:"kid"`
// Hosted Domain [only shows up for google eduction/for work/government domains]
Hd string `json:"hd"`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment