Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Created May 12, 2020 12:30
Show Gist options
  • Save salrashid123/23b8a666371cd5ccd3f8bcd5ca4a0105 to your computer and use it in GitHub Desktop.
Save salrashid123/23b8a666371cd5ccd3f8bcd5ca4a0105 to your computer and use it in GitHub Desktop.
Google ID Tokens with Golang
package main
import (
"context"
"io/ioutil"
"log"
"net/http"
"google.golang.org/api/idtoken"
)
const ()
// https://pkg.go.dev/google.golang.org/[email protected]/idtoken
func main() {
aud := "https://your.endpoint.run.url"
url := "https://httpbin.org/get"
jsonCert := "/path/to/svcaccount.json"
ctx := context.Background()
// With TokenSource
// With ADC
//ts, err := idtoken.NewTokenSource(ctx, aud)
// With ServiceAccount
ts, err := idtoken.NewTokenSource(ctx, aud, idtoken.WithCredentialsFile(jsonCert))
if err != nil {
log.Fatalf("unable to create TokenSource: %v", err)
}
tok, err := ts.Token()
if err != nil {
log.Fatalf("unable to retrieve Token: %v", err)
}
log.Printf("IDToken: %s", tok.AccessToken)
validTok, err := idtoken.Validate(ctx, tok.AccessToken, aud)
if err != nil {
log.Fatalf("token validation failed: %v", err)
}
if validTok.Audience != aud {
log.Fatalf("got %q, want %q", validTok.Audience, aud)
}
// With Authorized Client
client, err := idtoken.NewClient(ctx, aud, idtoken.WithCredentialsFile(jsonCert))
if err != nil {
log.Fatalf("Could not generate NewClient: %v", err)
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatalf("Error Creating HTTP Request: %v", err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error making authenticated call: %v", err)
}
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error Reading response body: %v", err)
}
bodyString := string(bodyBytes)
log.Printf("Authenticated Response: %v", bodyString)
}
@LetLifeStop
Copy link

hi~ I have a question. I want to know how to generate the token to visit gcp? I want to build a kubeConfig to visit gcp in this format.

apiVersion: v1
kind: Config
clusters:
- name: "my-gcp-cluster"
  cluster:
  certificate-authority-data: ......
  server: https://1.1.1.1
users:
- name: "my-gcp-cluster-user-name"
   user:
     token: "..."

I know how to get cluster.certificate-authority-data and cluster.server. But I use the token generated with the code in your example. It show this kubeConfig is "Invalid credentials".

@Teut2711
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment