javascript - Firebase Admin SDK GO VerifyIDToken 返回的不是 App Engine 上下文错误

标签 javascript firebase google-app-engine go firebase-authentication

我有一个使用 Firebase 进行身份验证的用户,我想做的是也在后端(Google 云平台/Go)上对该用户进行身份验证。我跟随了关于 Firebase 的文件

我在前端获取 idToken,并使用以下代码将 header 上的 token 发送到在我的本地主机上运行的服务器。

idToken = firebase.auth().currentUser.getIdToken()
axios({
    method: 'POST',
    url: 'https://localhost:8080/users',
    headers: {
      'Authentication-Token': idToken
    },
    data: {
        name: 'My name',
        user_name: 'my_user_name',
        email: 'example@example.com'
    }
})

在后端我想验证 idToken。我首先使用以下代码创建身份验证客户端。

opt := option.WithCredentialsFile("firebase_credential.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
client, err := app.Auth(context.Background())

使用客户端和来自前端的 idToken,我尝试了下面的代码。

t, err := client.VerifyIDToken(context.Background(), idToken)

这怎么会抛出

的错误
{"message":"Get https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com: oauth2: cannot fetch token: Post https://accounts.google.com/o/oauth2/token: not an App Engine context"}

我也尝试curl 向服务器发出相同的请求,但出现了相同的错误。

curl -X POST -H "Authentication-Token:hogehogemytoken" -d '{"name":"My name","user_name":"my user name","email":"example@example.com"}' http://localhost:8080/users

我很确定我正在发送正确的 token 。 有什么想法吗?

最佳答案

似乎在 appengine 标准环境中我不得不使用

ctx := appengine.NewContext(r)

而不是

ctx := context.Background()

在应用引擎请求上下文中,必须处理更复杂的事情,因为它们是 API 请求上下文。另一方面,通用 context.Background() 用于一般用途,因此与传入的 Http 请求无关。

所以我的解决方案是在 init.go 中传递 appengine.NewContext(r),如下所示。

r.POST("/users", func(c *gin.Context) { up.CreateUser(c, appengine.NewContext(c.Request)) })

将此应用引擎上下文传递给验证 token 。

func (c authClient) VerifyToken(ctx context.Context, token string) (IDToken, error) {
    opt := option.WithCredentialsFile("firebasecredential.json")
    app, err := firebase.NewApp(ctx, nil, opt)
    if err != nil {
        return nil, err
    }
    client, err := app.Auth(ctx)
    if err != nil {
        return nil, err
    }

    t, err := client.VerifyIDToken(ctx, token)
    if err != nil {
        return nil, err
    }
    return idToken{t}, nil
}

关于javascript - Firebase Admin SDK GO VerifyIDToken 返回的不是 App Engine 上下文错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837930/

相关文章:

JavaScript读取本地文件

javascript - 如何将 Yoast wordpress 插件添加到 laravel

ios - 在详细 Controller 中打开通知

python - 我该如何修复这个错误?坏键错误 : Name must be string type

google-app-engine - Dispatch.yaml 路由到特定模块版本?

python - 在 Python Google App Engine 上使用 SignedJwtAssertionCredentials

javascript - 在 ReactJS 中从组件状态传递样式

javascript - 无法实现自动前进整页 slider

firebase - Flutter firebase 软件包版本在消息传递、核心和分析之间发生冲突

python - 如何在 Firebase 中循环 UID