Skip to content

Instantly share code, notes, and snippets.

@ptone
Forked from wlhee/exmaple.go
Last active June 17, 2019 23:43
Show Gist options
  • Save ptone/6fdcbc1b311b77f3a915b9f71763ec55 to your computer and use it in GitHub Desktop.
Save ptone/6fdcbc1b311b77f3a915b9f71763ec55 to your computer and use it in GitHub Desktop.
Generate Open ID Token Connect with Google Service Account Key
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/coreos/go-oidc"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var (
keyFile = flag.String("key-file", "", "private pem key file for the service account")
url = flag.String("url", "", "target url")
)
func client(ctx context.Context, keyFile, targetAudience string) (*http.Client, error) {
// Read the key file bytes for the private key.
keyBytes, err := ioutil.ReadFile(keyFile)
if err != nil {
return nil, err
}
cfg, err := google.JWTConfigFromJSON(keyBytes)
if err != nil {
return nil, err
}
cfg.PrivateClaims = map[string]interface{}{"target_audience": targetAudience}
cfg.UseIDToken = true
return cfg.Client(ctx), nil
}
func main() {
flag.Parse()
if *keyFile == "" || *url == "" {
log.Fatal("Please specifiy --key-file <service_account_key> and --url <URL>")
}
cl, err := client(context.Background(), *keyFile, *url)
if err != nil {
log.Fatal("%v", err)
}
resp, err := cl.Get(*url)
if err != nil {
log.Fatal("%v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal("%v", err)
}
fmt.Printf("%s", string(body))
t, err := cl.Transport.(*oauth2.Transport).Source.Token()
if err != nil {
log.Fatal(err)
}
// Validation:
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, "https://accounts.google.com")
// var verifier = provider.Verifier(&oidc.Config{SkipClientIDCheck: true})
var verifier = provider.Verifier(&oidc.Config{ClientID: *url})
_, err = verifier.Verify(ctx, t.AccessToken)
if err != nil {
log.Fatal(err)
}
fmt.Println("token OK")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment