我已经使用Express在node中编写了api并将其托管在Firebase函数上。我正在尝试使用Firebase身份验证来保护api。
在用户使用Google身份验证登录到我的android应用程序后,我正在获取fire base jwt令牌并在Authoration标头中使用它。但是我得到了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 admin 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);
我也尝试使用不同的火力基地帐户,但它不起作用。
我做错了什么。
我终于明白了。拆分JWT令牌时出错了
idToken = req.headers.authorization.split('Bearer ')[1]; -->needed a space