使用Go进行Google服务帐号JWT授权

huangapple go评论77阅读模式
英文:

Google service account authorization with JWT in Go

问题

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

英文:

How do I authorize a service account with JWT in Go?

答案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) {
	// 读取私钥的pem文件字节。
	keyBytes, err := ioutil.ReadFile(*keyPath)
	if err != nil {
		return "", err
	}

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

	// 获取访问令牌。
	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)
  }
}
英文:

Use https://code.google.com/p/goauth2/

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

Get your service email and your p12 private key from the Google API Console. For now it can't read p12 files so strip them to just the rsa key with openssl
openssl pkcs12 -in file.p12 -nocerts -out key.pem -nodes then delete the extra text

Then:

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)
  }

huangapple
  • 本文由 发表于 2013年3月13日 08:04:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/15374625.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定