如何验证自定义令牌?

3
我正在使用Firebase身份验证和函数来完成我的项目。我的数据库API是由另一个提供商提供的。我需要以“管理员”的身份从函数中发出一些对我的数据库的调用。我的服务器已设置为通过以下配置验证Firebase的JWT令牌(自定义验证,无法使用Firebase管理员):
{
   "type":"RS256",
"jwk_url":"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",
   "audience":"<firebase-project-id>",
   "issuer":"https://securetoken.google.com/<firebase-project-id>"
}

这可以正确验证ID令牌,但无法解析由admin.auth().createCustomToken创建的自定义令牌,并显示以下错误:

无法验证JWT:JWSError JWSInvalidSignature

因此,除非我能以某种方式验证它们,否则我无法使用自定义令牌来验证我的云函数?

这是生成我的函数令牌的方法:

  const uid = "function-worker";
  const claims = {
    "https://hasura.io/jwt/claims": {
      "x-hasura-default-role": "function",
      "x-hasura-allowed-roles": ["function"],
      "x-hasura-user-id": uid,
    },
  };
  const jwt = await admin.auth().createCustomToken(uid, claims);

生成的jwt随后按照https://github.com/hasura/graphql-engine/tree/master/community/sample-apps/firebase-jwt中的说明发送到我的hasura服务器。

上述指南适用于id令牌,但不适用于自定义令牌。有关hasura服务器如何处理jwt验证的更详细说明,请参见https://github.com/hasura/graphql-engine/blob/dcab20a5ee388ebd754a7828de1309a3a2e0eaee/docs/graphql/manual/auth/authentication/jwt.rst#generating-jwt-config


请编辑问题,展示你正在使用的代码,说明它没有按照你的预期工作。 - undefined
@DougStevenson 添加 - undefined
你是如何验证它的?我有点期望能看到一些调用 verifyIdToken 的代码。 - undefined
@DougStevenson 的验证是由 Hasura GraphQL 服务器完成的,而不使用管理员 SDK。他们只要求提供像我上面发布的 JSON 配置。我相信验证是在这里完成的(这不是 Firebase 支持的语言)https://github.com/hasura/graphql-engine/blob/d52bfcda4ebf5ac6f4f013b2d5ed698010d72a51/server/src-lib/Hasura/Server/Auth/JWT.hs#L211 - undefined
@DougStevenson 这里是他们如何做到的详细解释 https://github.com/hasura/graphql-engine/blob/dcab20a5ee388ebd754a7828de1309a3a2e0eaee/docs/graphql/manual/auth/authentication/jwt.rst#generating-jwt-config - undefined
2个回答

6

0

在Firebase函数上生成ID令牌

1 - REST API

import fetch from 'node-fetch';
...
const customToken = await admin.auth().createCustomToken(user.uid);
const tokenURL = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=';

const response = await fetch(tokenURL + API_KEY, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    token: customToken,
    returnSecureToken: true
  })
}).then(r => r.json());

console.log(response.idToken);

2 - 服务器上的 Firebase 客户端

import firebase from "firebase/app";
import "firebase/auth";

admin.initializeApp();
firebase.initializeApp(firebase_config);
...

const token: any = await admin.auth().createCustomToken(user.uid)
.then((customToken: string) =>
  // use custom token to get firebase token
  firebase.auth().signInWithCustomToken(customToken)
    .then((cred: firebase.auth.UserCredential) => cred.user?.getIdToken()))
.catch((e: string) => console.error(e));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接