如何在Go中的App Engine上使用OAuth2的客户端ID?

时间:2013-04-22 11:30:45

标签: google-app-engine go google-oauth

我在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!")
}

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

令牌配置不够用;首先必须通过以下步骤获得有效的访问令牌:

  1. 将用户重定向到AuthCodeURL返回的页面。将向用户显示应用程序的名称和请求的权限。

  2. 如果用户授予权限,则会将其重定向到您在配置中提供的RedirectURL。该URL将包含名为code

  3. 的查询参数
  4. 检索code参数并将其传递给Exchange。如果一切顺利,现在应该正确验证请求。