Skip to content

Instantly share code, notes, and snippets.

@wlhee
Last active Jun 17, 2019
Embed
What would you like to do?
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