Last active
June 17, 2019 23:25
-
-
Save wlhee/64bc518190053e2122ca1909c2977c67 to your computer and use it in GitHub Desktop.
Generate Open ID Token Connect with Google Service Account Key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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