我想弄清楚如何在 golang 中存储 OAuth2 凭据?
目前我在 Python 中执行此操作:
从 oauth2client.file 导入存储 ... storage = Storage('settings.dat')
go中有没有类似的东西?有人有例子吗?谢谢!
我想弄清楚如何在 golang 中存储 OAuth2 凭据?
目前我在 Python 中执行此操作:
从 oauth2client.file 导入存储 ... storage = Storage('settings.dat')
go中有没有类似的东西?有人有例子吗?谢谢!
我认为您想要一个 CacheFile 作为 TokenCache 传递。这是从使用 oauth2 的 google drive 的项目中提取的一些代码,希望可以帮助您入门!
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)
}
}
}