【问题标题】:Firebase Admin SDK GO VerifyIDToken returns not an App Engine context errorFirebase Admin SDK GO VerifyIDToken 返回不是 App Engine 上下文错误
【发布时间】:2018-02-17 04:43:08
【问题描述】:

我有一个通过 Firebase 身份验证的用户,我想做的是在后端(谷歌云平台/Go)上对该用户进行身份验证。我跟着Firebase上的文档进行操作

我在前端获取 idToken,然后使用以下代码将标头上的令牌发送到在我的本地主机上运行的服务器。

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

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

【问题讨论】:

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


【解决方案1】:

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

ctx := appengine.NewContext(r)

而不是

ctx := context.Background()

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

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

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

将此 appengine 上下文传递给验证令牌。

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
}

【讨论】:

    【解决方案2】:

    VerifyIDToken 不支持上下文,请检查documentation 截至目前:

    func (c *Client) VerifyIDToken(idToken string) (*Token, error)
    

    您评论中的link 指向Future Request (FR),这意味着它尚未实现,因此它不是错误。

    您可以使用VerifyIDTokenAndCheckRevoked 做:

    func (c *Client) VerifyIDTokenAndCheckRevoked(ctx context.Context, idToken string) (*Token, error)
    

    【讨论】:

      猜你喜欢
      • 2013-10-25
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2017-07-14
      • 2015-03-27
      • 2012-06-22
      相关资源
      最近更新 更多