Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active January 26, 2021 00:44
Show Gist options
  • Save tanaikech/4b4cb27ece27573b3f4df0e050b52330 to your computer and use it in GitHub Desktop.
Save tanaikech/4b4cb27ece27573b3f4df0e050b52330 to your computer and use it in GitHub Desktop.
Retrieving Access Token using Service Account by Google's OAuth2 package

Retrieving Access Token using Service Account by Google's OAuth2 package for Golang

This is a sample golang script for retrieving access token using Service Account of Google by Google's OAuth2 package.

The script without using Google's OAuth2 package is here.

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "golang.org/x/oauth2/jwt"
)

func serviceAccount(credentialFile string) (*oauth2.Token, error) {
    b, err := ioutil.ReadFile(credentialFile)
    if err != nil {
        return nil, err
    }
    var c = struct {
        Email      string `json:"client_email"`
        PrivateKey string `json:"private_key"`
    }{}
    json.Unmarshal(b, &c)
    config := &jwt.Config{
        Email:      c.Email,
        PrivateKey: []byte(c.PrivateKey),
        Scopes: []string{
            "https://www.googleapis.com/auth/drive.metadata.readonly",
        },
        TokenURL: google.JWTTokenURL,
    }
    token, err := config.TokenSource(oauth2.NoContext).Token()
    if err != nil {
        return nil, err
    }
    return token, nil
}

func main() {
    token, err := serviceAccount("credentials.json") // Please set here
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    fmt.Println(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment