Skip to content

Instantly share code, notes, and snippets.

@wlhee
Last active June 17, 2019 23:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wlhee/64bc518190053e2122ca1909c2977c67 to your computer and use it in GitHub Desktop.
Save wlhee/64bc518190053e2122ca1909c2977c67 to your computer and use it in GitHub Desktop.
Generate Open ID Token Connect with Google Service Account Key
package main
import (
"context"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"golang.org/x/oauth2/google/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))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment