Firebase Admin SDK GO验证返回不是应用引擎上下文错误



我有一个用firebase认证的用户,我想做的就是在后端(Google Cloud Platform/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())

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

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

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

看来,在附录标准环境中,我必须使用

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)) })

将这个附录上下文传递给验证令牌。

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
}

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

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

您的评论中的链接指向未来请求(FR(,这意味着它尚未实现,因此它不是错误。

您可以使用VerifyIDTokenAndCheckRevoked确实:

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

最新更新