How to generate an access token from a service account created from firebase app using Go

Viewed 46

There's a way to generate an access token using a service account file generated from the firebase app. Source: https://firebase.google.com/docs/database/rest/auth#python.

Is there a way to generate an access token from a Go SDK?

[Update] I've studied their doc and reached this level and am kinda lost on how to fetch/get the access_token from that point.

package main

import (
    "context"
    "fmt"
    "math"
    "regexp"
    "sort"
    "strconv"
    "strings"

    "google.golang.org/api/oauth2/v2"
    "google.golang.org/api/option"
)
func main() {
    ctx := context.Background()
    oauth2Service, err := oauth2.NewService(ctx, option.WithCredentialsFile("service-account.json"), option.WithScopes("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database"))

    if err != nil {
        panic(err.Error())
    }
    tokenInfo, err := oauth2Service.Tokeninfo().Do()

    if err != nil {
        panic(err.Error())
    }
    
    fmt.Println(tokenInfo)
}
1 Answers

Just got the solution after digging more into their docs: Doc to transport package

    ctx := context.Background()
    creds, err := transport.Creds(ctx, option.WithCredentialsFile("service-account.json"), option.WithScopes("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database"))

    if err != nil {
        panic(err.Error())
    }

    ts := creds.TokenSource

    tok, err := ts.Token()

    if err != nil {
        panic(err.Error())
    }

    fmt.Printf("access_token %v", tok.AccessToken)
Related