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)
            }
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看