3

如何在 Go 中使用 JWT 授权服务帐户?

4

1 回答 1

7

使用https://code.google.com/p/goauth2/

go get code.google.com/p/goauth2/oauth

从 Google API 控制台获取您的服务电子邮件和 p12 私钥。目前它无法读取 p12 文件,因此使用 openssl 将它们剥离为 rsa 键, openssl pkcs12 -in file.p12 -nocerts -out key.pem -nodes然后删除多余的文本

然后:

package main

import (
  "code.google.com/p/goauth2/oauth/jwt"
  "flag"
  "fmt"
  "http"
  "io/ioutil"
)

var (
  serviceEmail = flag.String("service_email", "", "OAuth service email.")
  keyPath      = flag.String("key_path", "key.pem", "Path to unencrypted RSA private key file.")
  scope        = flag.String("scope", "", "Space separated scopes.")
)

func fetchToken() (string, error) {
    // Read the pem file bytes for the private key.
    keyBytes, err := ioutil.ReadFile(*keyPath)
    if err != nil {
        return "", err
    }

    t := jwt.NewToken(*serviceEmail, *scope, keyBytes)
    c := &http.Client{}

    // Get the access token.
    o, err := t.Assert(c)
    if err != nil {
        return "", err
    }
    return o.AccessToken, nil
}

func main() {
  flag.Parse()
  token, err := fetchToken()
  if err != nil {
    fmt.Printf("ERROR: %v\n", err)
  } else {
    fmt.Printf("SUCCESS: %v\n", token)
  }
于 2013-03-13T00:04:59.577 回答