在golang中存储Oauth2凭据

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

Storing Oauth2 Credentials in golang

问题

我正在尝试弄清楚如何在golang中存储OAuth2凭据。

目前我在Python中这样做:

from oauth2client.file import Storage
...
storage = Storage('settings.dat')

在go语言中是否有类似的方法?有人有示例吗?谢谢!

英文:

I am trying to figure out how I can storing OAuth2 credentials in golang?

Currently I do this in Python:

from oauth2client.file import Storage
...
storage = Storage('settings.dat')

Is there anything similar in go? Does anyone have an example? Thanks!

答案1

得分: 3

我认为你想要一个作为TokenCache传递的CacheFile。以下是从一个使用Google Drive和OAuth2的项目中提取的一些代码,希望能帮助你入门!

import "code.google.com/p/goauth2/oauth"

// 请求用户进行新的授权
func MakeNewToken(t *oauth.Transport) error {
    if *driveAuthCode == "" {
        // 生成授权链接
        authUrl := t.Config.AuthCodeURL("state")
        fmt.Fprintf(os.Stderr, "请在浏览器中打开以下链接\n")
        fmt.Fprintf(os.Stderr, "%s\n", authUrl)
        fmt.Fprintf(os.Stderr, "登录后,使用 -drive-auth-code 参数重新运行此程序\n")
        fmt.Fprintf(os.Stderr, "在创建了驱动令牌文件之前,只需要运行一次此参数\n")
        return errors.New("请使用 --drive-auth-code 重新运行")
    }

    // 读取授权码,并交换为令牌
    //fmt.Printf("请输入验证码: ")
    //var code string
    //fmt.Scanln(&code)
    _, err := t.Exchange(*driveAuthCode)
    return err
}

func main() {
    // 授权设置
    var driveConfig = &oauth.Config{
        ClientId:     *driveClientId,
        ClientSecret: *driveClientSecret,
        Scope:        "https://www.googleapis.com/auth/drive",
        RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
        AuthURL:      "https://accounts.google.com/o/oauth2/auth",
        TokenURL:     "https://accounts.google.com/o/oauth2/token",
        TokenCache:   oauth.CacheFile(*driveTokenFile),
    }

    t := &oauth.Transport{
        Config:    driveConfig,
        Transport: http.DefaultTransport,
    }

    // 尝试从缓存中获取令牌;如果失败,则需要获取一个新的令牌
    token, err := driveConfig.TokenCache.Token()
    if err != nil {
        err := MakeNewToken(t)
        if err != nil {
            return nil, fmt.Errorf("授权失败:%s", err)
        }
    }
}
英文:

I think you want a CacheFile which you pass as the TokenCache. Here is some code ripped from a project which uses google drive with oauth2 which should hopefully get you started!

import "code.google.com/p/goauth2/oauth"
// Ask the user for a new auth
func MakeNewToken(t *oauth.Transport) error {
if *driveAuthCode == "" {
// Generate a URL to visit for authorization.
authUrl := t.Config.AuthCodeURL("state")
fmt.Fprintf(os.Stderr, "Go to the following link in your browser\n")
fmt.Fprintf(os.Stderr, "%s\n", authUrl)
fmt.Fprintf(os.Stderr, "Log in, then re-run this program with the -drive-auth-code parameter\n")
fmt.Fprintf(os.Stderr, "You only need this parameter once until the drive token file has been created\n")
return errors.New("Re-run with --drive-auth-code")
}
// Read the code, and exchange it for a token.
//fmt.Printf("Enter verification code: ")
//var code string
//fmt.Scanln(&code)
_, err := t.Exchange(*driveAuthCode)
return err
}
func main() {
// Settings for authorization.
var driveConfig = &oauth.Config{
ClientId:     *driveClientId,
ClientSecret: *driveClientSecret,
Scope:        "https://www.googleapis.com/auth/drive",
RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
AuthURL:      "https://accounts.google.com/o/oauth2/auth",
TokenURL:     "https://accounts.google.com/o/oauth2/token",
TokenCache:   oauth.CacheFile(*driveTokenFile),
}
t := &oauth.Transport{
Config:    driveConfig,
Transport: http.DefaultTransport,
}
// Try to pull the token from the cache; if this fails, we need to get one.
token, err := driveConfig.TokenCache.Token()
if err != nil {
err := MakeNewToken(t)
if err != nil {
return nil, fmt.Errorf("Failed to authorise: %s", err)
}
}
}

huangapple
  • 本文由 发表于 2013年8月14日 00:17:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/18214173.html
匿名

发表评论

匿名网友

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

确定