Skip to content

Instantly share code, notes, and snippets.

@utahta
Created April 12, 2018 10:34
Show Gist options
  • Save utahta/08e142798aa05b939ec7f6242842e213 to your computer and use it in GitHub Desktop.
Save utahta/08e142798aa05b939ec7f6242842e213 to your computer and use it in GitHub Desktop.
Cloud IAP経由で渡されたJWTのパースを試みる
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/dgrijalva/jwt-go"
"gopkg.in/square/go-jose.v2"
)
func main() {
// example for Cloud IAP
// https://cloud.google.com/iap/docs/signed-headers-howto
tokenString := "XXX"
parser := &jwt.Parser{
SkipClaimsValidation: true,
}
token, _, err := parser.ParseUnverified(tokenString, jwt.MapClaims{})
if err != nil {
log.Fatal(err)
}
kid := token.Header["kid"].(string)
resp, err := http.Get("https://www.gstatic.com/iap/verify/public_key-jwk")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
token, err = jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
var ks jose.JSONWebKeySet
json.Unmarshal(b, &ks)
return ks.Key(kid)[0].Key, nil
})
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
fmt.Printf("%v\n", claims)
} else {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment