为OAuth2提供程序正确的AppEngine Golang包

时间:2016-06-19 19:25:19

标签: google-app-engine go

使用OAuth和

的正确方法是什么

如果我使用context.Context中的golang.org/x/net/context,则错误为:

"golang.org/x/net/context".Context does not implement "appengine".Context (missing Call method)

但如果我使用appengine.Context(SDK)中的appengine,则错误为:

cannot use oauth2.NewClient(c) (type *http.Client) as type "golang.org/x/net/context".Context in argument to provider.Client:
*http.Client does not implement "golang.org/x/net/context".Context (missing Deadline method)

如果我使用oauth2.NoContext,则运行时错误为

Post https://accounts.google.com/o/oauth2/token: not an App Engine context

均使用Go 1.4和1.7b3进行测试

使用这段代码:

func Public_YoutubeOauth(w http.ResponseWriter, r *http.Request) {
    c := appengine.NewContext(r)
    provider, csrf := getOAuth(r)
    gets, err := url.ParseQuery(r.URL.RawQuery)
    if RenderHtmlIfError(w,err) {
        return
    }
    if csrf != gets.Get(`state`) {
        RenderHtmlError(w,`incorrect CSRF state`)
        return
    }
    code := gets.Get(`code`)
    token, err := provider.Exchange(c, code) // error here
    if RenderHtmlIfError(w,err) {
        return
    }
    RenderHtml(w,`page`,map[string]interface{`token`:token})
}

provider是:

&oauth2.Config{
        ClientID:     `aaa`,
        ClientSecret: `bbb`,
        RedirectURL:  url + `/foo/youtube_oauth`,
        Scopes: []string{
            `openid`,
            `email`,
            `profile`,
            `https://www.googleapis.com/auth/youtube`,
        },
        Endpoint: google.Endpoint,
    }

解决这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

解决方案:

  1. 将所有:)导入更改为"appengine
  2. 继续使用"google.golang.org/appengine(来自context.Context)代替golang.org/x/net/context