1

我在 AppEngine 中运行了一些相当简单的 Go 代码,应该使用 OAuth2 从用户帐户中获取文件列表。似乎可以初始化服务,但是当它尝试获取文件列表时,出现此错误: OAuthError:RoundTrip:未提供令牌

package foo

import (
    "appengine"
    "appengine/urlfetch"
    "code.google.com/p/goauth2/oauth"
    "code.google.com/p/google-api-go-client/drive/v2"
    "fmt"
    "net/http"
)

var config = &oauth.Config{
    ClientId:     "(redacted).apps.googleusercontent.com",
    ClientSecret: "REDACTED",
    Scope:        "https://www.googleapis.com/auth/drive",
    AuthURL:      "https://accounts.google.com/o/oauth2/auth",
    TokenURL:     "https://accounts.google.com/o/oauth2/token",
}

func init() {
    http.HandleFunc("/", home)
}

func home(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    transport := &oauth.Transport{
        Config:    config,
        Transport: &urlfetch.Transport{Context: c}}
    svc, err := drive.New(transport.Client())
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    q := svc.Files.List()
    _, err = q.Do()
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    fmt.Fprintf(w, "Success!")
}

我无法弄清楚我在这里做错了什么。任何帮助将不胜感激。

4

2 回答 2

3

这个页面有点旧,但它用 Go 代码很好地概述了这些步骤。 http://golangtutorials.blogspot.com/2011/11/oauth2-3-legged-authorization-in-go-web.html

于 2013-05-11T02:38:59.967 回答
1

The token configuration is not enough; you first have to get a valid access token with the following steps:

  1. Redirect the user to the page returned by AuthCodeURL. The user will be shown the name of your application and the requested permissions.

  2. If the user grants the permissions, they will be redirected to the RedirectURL you gave in the configuration. The URL will contain a query parameter named code.

  3. Retrieve the code parameter and pass it to Exchange. If everything went well, the requests should now be authenticated properly.

于 2013-04-22T16:50:04.710 回答