在golang中存储Oauth2凭据

时间:2013-08-13 16:17:14

标签: go

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

目前我在Python中这样做:

来自oauth2client.file导入存储 ... storage =存储('settings.dat')

有什么相似之处吗?有人有例子吗?谢谢!

1 个答案:

答案 0 :(得分:2)

我想你想要a CacheFile which you pass as the TokenCache。以下是从使用带有oauth2的google驱动器的项目中删除的一些代码,希望能帮助您入门!

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