Skip to content

Instantly share code, notes, and snippets.

@ubaidillahhf
Last active October 6, 2023 05:42
Show Gist options
  • Select an option

  • Save ubaidillahhf/33ec3e4a7e68fba8dbe8a5f2edf9ed52 to your computer and use it in GitHub Desktop.

Select an option

Save ubaidillahhf/33ec3e4a7e68fba8dbe8a5f2edf9ed52 to your computer and use it in GitHub Desktop.
Google API Oauth2 JWT Token
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)
func main() {
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/google-token", func(w http.ResponseWriter, r *http.Request) {
token := getTokenGoogle()
w.Write([]byte(token))
})
http.ListenAndServe(":3000", r)
}
func getTokenGoogle() string {
token, err := serviceAccount("key_account.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return token.AccessToken
}
func serviceAccount(credentialFile string) (*oauth2.Token, error) {
b, err := os.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://mail.google.com/",
// can use other scopes google api...
},
TokenURL: google.JWTTokenURL,
Expires: time.Hour,
Subject: "sender@gmail.co",
}
token, err := config.TokenSource(context.Background()).Token()
if err != nil {
return nil, err
}
return token, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment