go - 在 golang 中存储 Oauth2 凭证

标签 go

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

目前我在 Python 中这样做:

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

go有类似的吗?有人有例子吗?谢谢!

最佳答案

我想你想要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)
        }
     }
}

关于go - 在 golang 中存储 Oauth2 凭证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214173/

相关文章:

go - 当方法实际上没有丢失时接口(interface)转换 panic

templates - Golang http/模板变量

go - 加密的确定性伪随机字节

database - UnixNano 与服务器 ID 串联是一个好的主键吗?

user-interface - 编写确认(是/否)对话框

时间格式化和从字符串转换

pointers - 为什么在本 golang 教程中将指针用于结构实例?

Go Web 服务 - 未定义的类型没有字段或方法

javascript - Go lang 执行 javascript 以检索页面中的文本

go - 防止 golang http.NewRequest 向 POST 正文添加大括号