在golang中存储Oauth2凭据

在golang中存储Oauth2凭据,go,Go,我想知道如何在golang中存储OAuth2凭据 目前我使用Python执行此操作: 从oauth2client.file导入存储 ... 存储=存储('settings.dat') 围棋里有类似的东西吗?有人举个例子吗?谢谢 我想你想要。下面是从一个使用GoogleDrive和oauth2的项目中提取的一些代码,希望能帮助您开始 import "code.google.com/p/goauth2/oauth" // Ask the user for a new auth func MakeN

我想知道如何在golang中存储OAuth2凭据

目前我使用Python执行此操作:

从oauth2client.file导入存储 ... 存储=存储('settings.dat')

围棋里有类似的东西吗?有人举个例子吗?谢谢

我想你想要。下面是从一个使用GoogleDrive和oauth2的项目中提取的一些代码,希望能帮助您开始

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

也许这就是您所需要的:如果您希望简单地存储您的客户端凭据(即,您的应用程序可以针对OAuth2服务器进行身份验证),那么只需将它们存储在环境变量或设置文件中(JSON很好),并在应用程序启动时使用
os.GetEnv
encoding/JSON
获取它们(使用
init()
)。这意味着密钥不会被编译到你的应用程序中,可以在不重新编译的情况下进行旋转/更新。@elithrar这不是我想做的,多亏了这一点,它是写入某个静态文件还是只是临时存储在内存中?写入一个文件-由
*driveTokenFile
指定的文件。添加了一个指向文档的链接。看起来
code.google.com/p/goauth2
已被弃用,取而代之的是
golang.org/x/oauth2
,但似乎已删除
CacheFile
。我看到了一个示例,但没有示例说明如何使用它来保存凭据,而不必每次都强制用户通过接受流。