使用jsonwebtoken时,验证firebase自定义令牌以获取令牌ID失败

Har*_*oln 10 node.js jwt firebase firebase-admin

在后端,通过firebase的管理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);
    });
});
Run Code Online (Sandbox Code Playgroud)

然后客户端前端应用程序选择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);
  });
Run Code Online (Sandbox Code Playgroud)

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

这需要签名吗?如果有人能解释这个或有任何指针?

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

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

Hir*_*aka 13

看起来你正在verifyIdToken使用自定义令牌进行调用.那不行.verifyIdToken只接受"ID令牌".从自定义令牌首次调用获取ID令牌signInWithCustomToken().然后调用getToken()已登录的用户实例.

  • 非常感谢 :) (2认同)

Fla*_*jta 8

如果您不想使用 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
            })
        }
    })
Run Code Online (Sandbox Code Playgroud)