【问题标题】:Verifying firebase custom token to get token ID fails when using jsonwebtoken使用 jsonwebtoken 时验证 firebase 自定义令牌以获取令牌 ID 失败
【发布时间】:2019-09-15 22:40:26
【问题描述】:

因此,在后端通过 firebase 的 admin SDK 生成了一个自定义令牌:

router.use('/get-token', (req, res) => {
    var uid = "big-secret";
    admin.auth().createCustomToken(uid)
      .then(function(customToken) {
        res.json({
          instanceID: customToken
        });
      })
      .catch(function(error) {
        console.log("Error creating custom token:", error);
    });
});

客户端前端应用程序然后获取 customToken 并向后端发出请求以进行验证:

const fbPrivateKey = serviceAccount.private_key;
const key = new NodeRSA(fbPrivateKey).exportKey('pkcs8-public-pem');
router.get('/verifyIdToken', cors(), (req, res) => {
  jwt.verify(req.headers.authorization.split('Bearer ')[1], key, { algorithms: ['RS256'] }, function(err, decoded) {
    console.log('err', err);
    console.log('decoded', decoded);
  });

这总是错误的消息:JsonWebTokenError: invalid signature

这需要签名吗?如果有人可以解释一下或有任何指示吗?

更新: 当运行req.headers.authorization.split('Bearer ')[1]jwt.io 时,表示签名无效,但随后我输入我的私钥(key)并验证。

我是否得到了不正确的方法调用或将错误的参数传递给jwt.verify()

【问题讨论】:

    标签: node.js firebase jwt firebase-admin


    【解决方案1】:

    您似乎正在使用自定义令牌调用 verifyIdToken。那是行不通的。 verifyIdToken 只接受“ID 令牌”。要从自定义令牌中获取 ID 令牌,首先调用 signInWithCustomToken()。然后在登录的用户实例上调用getToken()

    【讨论】:

    • 非常感谢 :)
    • 这个答案令人困惑,您所说的是 admin.auth().verifyIdToken() ,是的,它只能验证 ID 令牌而不是自定义令牌。但在帖子中,这并没有在任何地方使用,/verifyIdToken 只是 Harry 配置用于验证 id 的路由。我认为@Harry 只是导出了错误的公钥,请在下面查看我的答案。
    【解决方案2】:

    如果您不想使用 signInWithCustomToken() 这是正确的方法

    const publicKey = new NodeRSA().importKey(serviceAccount.private_key, "pkcs8-private-pem").exportKey("pkcs8-public-pem")
    
    jwt.verify(token, publicKey, {
            algorithms: ["RS256"]
        }, (err, decoded) => {
            if (err) {
                # send some error response
                res.status(400).json({
                    status: 0,
                    message: "Token is invalid!"
                })
            } else {
                # send some valid response
                res.status(200).json({
                    status: 1,
                    message: "Token is valid for uid " + decoded.uid
                })
            }
        })
    

    【讨论】:

    • 您可能不需要公钥。使用 jsonwebtoken 包(repo:github.com/auth0/node-jsonwebtoken),您可以将 serviceAccount.private_key 作为第二个参数发送,因此不需要 NodeRSA。
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 2018-07-23
    • 2016-09-27
    • 1970-01-01
    • 2019-06-28
    • 2023-04-06
    • 2023-03-12
    • 2021-09-12
    相关资源
    最近更新 更多