google-app-engine - Martini oauth2callback适配GAE后重定向到oauth2error

标签 google-app-engine go oauth-2.0 facebook-oauth martini

下面的代码在本地服务器上完美运行,但是当适应谷歌应用引擎时(func main 更改为 init 并且包名称从 main 设置为测试应用程序)oauth2callback 请求不再工作,下面的请求被重定向到 oauth2error 处理程序.

http://testapp.com/oauth2callback?code=OAUTHRESPONSEFROMFACEBOOK&state=%2F

package testapp

import (
    "github.com/go-martini/martini"
    goauth2 "github.com/golang/oauth2"
    "github.com/martini-contrib/oauth2"
    "github.com/martini-contrib/sessions"
    "net/http"
)

func init() {
    m := martini.Classic()
    m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
    m.Use(oauth2.Facebook(
        goauth2.Client("AppID", "AppSecret"),
        goauth2.RedirectURL("http://testapp.com/oauth2callback"),
        goauth2.Scope("email,user_birthday,user_friends,publish_actions,user_location,user_photos"),
    ))
    // Tokens are injected to the handlers
    m.Get("/", func(tokens oauth2.Tokens) string {
        if tokens.Expired() {
            return "not logged in, or the access token is expired"
        }
        return "logged in"
    })

    // Routes that require a logged in user
    // can be protected with oauth2.LoginRequired handler.
    // If the user is not authenticated, they will be
    // redirected to the login path.
    m.Get("/restrict", oauth2.LoginRequired, func(tokens oauth2.Tokens) string {
        return tokens.Access()
    })

    http.Handle("/", m)
}

最佳答案

我的猜测是您需要将 App Engine 上下文注入(inject)到 Get 方法中。

根据 this issue在 Go Martini 仓库中,您可以执行以下操作:

func AppEngine(m martini.Context, r *http.Request) {
    m.MapTo(appengine.NewContext(r), (*appengine.Context)(nil))
}

func init() {
    m := martini.Classic()
    m.Use(AppEngine)

    // ...

    m.Get("/", func(tokens oauth2.Tokens, c appengine.Context) string {
        if tokens.Expired() {
            return "not logged in, or the access token is expired"
        }
        return "logged in"
    })

    m.Get("/restrict", oauth2.LoginRequired, func(tokens oauth2.Tokens, c appengine.Context) string {
        return tokens.Access()
    })
}

关于google-app-engine - Martini oauth2callback适配GAE后重定向到oauth2error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27459345/

相关文章:

python - 没有 Web 服务的 Bigquery cron 作业

go - go map值和nil之间的差异

go - 输入字节 68 处的非法 base64 数据

java - Google Oauth2刷新 token 为空

java - 使用 appcfg.py 更新数据存储实体重命名主键

google-app-engine - 找不到导入 : "code.google.com/p/goauth2/oauth"

php - 谷歌 PHP API : "invalid response from api server"

go - big.Float SetPrec 奇怪的行为

c# - 获取有关谁安装了 Microsoft Teams Bot 应用的信息

android - 在 Google App Engine 上,我可以关联 Google OAuth 2 token 和使用 Android 的 AccountManager 获得的 SACSID token 吗?