Skip to content

Instantly share code, notes, and snippets.

@salrashid123
Last active August 31, 2023 15:18
Show Gist options
  • Save salrashid123/efe4b455f8ed19ea888d773d239ca2ff to your computer and use it in GitHub Desktop.
Save salrashid123/efe4b455f8ed19ea888d773d239ca2ff to your computer and use it in GitHub Desktop.
GCP JWTAccessTokens for BQ APIs
/*
see
https://developers.google.com/identity/protocols/oauth2/service-account#jwt-auth
for TPM https://github.com/salrashid123/oauth2#usage-tpmtokensource
*/
package main
import (
"context"
"flag"
"fmt"
"io/ioutil"
// "time"
"cloud.google.com/go/bigquery"
// "github.com/golang-jwt/jwt"
// "golang.org/x/oauth2"
//"golang.org/x/oauth2/google"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
)
var ()
func main() {
flag.Parse()
ctx := context.Background()
var aud string = "https://bigquery.googleapis.com/google.cloud.bigquery.v2.DatasetService"
// iat := time.Now()
// exp := iat.Add(1 * time.Hour)
// claims := &jwt.StandardClaims{
// IssuedAt: iat.Unix(),
// ExpiresAt: exp.Unix(),
// Issuer: "[email protected]",
// Subject: "[email protected]",
// Audience: aud,
// }
// signBytes, err := ioutil.ReadFile("/path/to/serviceaccountkeyaspem.pem")
// keyctx, err := jwt.ParseRSAPrivateKeyFromPEM(signBytes)
// if err != nil {
// panic(err)
// }
// token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
// tokenString, err := token.SignedString(keyctx)
// if err != nil {
// panic(err)
// }
// fmt.Printf(tokenString)
// s := oauth2.StaticTokenSource(
// &oauth2.Token{
// AccessToken: tokenString,
// Expiry: exp,
// TokenType: "Bearer",
// },
// )
keyBytes, err := ioutil.ReadFile("/path/to/serviceaccountkey.json")
if err != nil {
panic(err)
}
s, err := google.JWTAccessTokenSourceFromJSON(keyBytes, aud)
if err != nil {
panic(err)
}
client, err := bigquery.NewClient(ctx, "core-eso", option.WithTokenSource(s))
if err != nil {
panic(err)
}
defer client.Close()
it := client.Datasets(ctx)
for {
dataset, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
panic(err)
}
fmt.Println(dataset.DatasetID)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment