duanjinchi1982 2013-08-13 16:17
浏览 58
已采纳

在golang中存储Oauth2凭据

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条回答 默认 最新

  • douyi1197 2013-08-13 16:51
    关注

    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
    ")
            fmt.Fprintf(os.Stderr, "%s
    ", authUrl)
            fmt.Fprintf(os.Stderr, "Log in, then re-run this program with the -drive-auth-code parameter
    ")
            fmt.Fprintf(os.Stderr, "You only need this parameter once until the drive token file has been created
    ")
            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)
            }
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?