Firebase管理员SDK无法解码JWT令牌

时间:2019-05-06 13:32:49

标签: android firebase firebase-authentication jwt google-cloud-functions

我已经使用express在node中编写了api并将其托管在firebase函数上。我正在尝试使用Firebase身份验证来保护api。

用户使用Google身份验证登录到我的android应用程序后,我正在获取firebase jwt令牌并将其用于Authorization标头中。但是我得到了403未经授权。当我检查Firebase功能日志时,我看到了错误

Error while verifying Firebase ID token: { Error: Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token. See https://firebase.google.com/docs/auth/admin/verify-id-tokens for details on how to retrieve an ID token.
at FirebaseAuthError.FirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:42:28)
at FirebaseAuthError.PrefixedFirebaseError [as constructor] (/srv/node_modules/firebase-admin/lib/utils/error.js:88:28)

获取firebase jwt令牌的代码

 private fun updateUI(user: FirebaseUser) {
    user.getIdToken(false)
        .addOnCompleteListener {
            if (it.isSuccessful) {
                val token = it.result!!.token
                if (token != null) {
                    Timber.d("token: $token")
                    sharePref.put("token", token)
                    presenter.getData(1)
                }
            }
        }
    val header = navView.getHeaderView(0)
    header.user_name.text = user.displayName
    header.user_email.text = user.email
    picasso.load(user.photoUrl).into(header.imageView)
}

Firebase管理员SDK令牌验证的代码

var validateFirebaseIdToken = async function (req, res, next) {
    if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
        console.error('No Auth Headers Found')
        res.status(403).send('Unauthorized');
        return;
    }
    let idToken;
    if (req.headers.authorization && req.headers.authorization.startsWith('Bearer ')) {
        console.log('Found "Authorization" header');
        // Read the ID Token from the Authorization header.
        idToken = req.headers.authorization.split('Bearer')[1];
        console.log("fire token : "+idToken);
    }

    try {
        const decodedIdToken = await admin.auth().verifyIdToken(idToken);
        console.log('ID Token correctly decoded', decodedIdToken);
        req.user = decodedIdToken;
        next();
        return;
    } catch (error) {
        console.error('Error while verifying Firebase ID token:', error);
        res.status(403).send('Unauthorized');
        return;
    }
}
app.use(cookieParser);
app.use(validateFirebaseIdToken);

我也尝试过使用其他的Firebase帐户,但这没用。

我在做什么错了。

1 个答案:

答案 0 :(得分:0)

我终于明白了。拆分JWT令牌时发生错误

idToken = req.headers.authorization.split('Bearer ')[1]; -->needed a space