无法使用firebase.auth()

时间:2018-05-31 14:50:29

标签: firebase firebase-authentication

在我的客户端上使用OAuth和Github,我将带有结果令牌的获取请求发送到我的服务器。我按预期获取令牌,但无法执行firebase.auth()。verifyIdToken以获取令牌。我的SDK使用admin SDK setup之后的证书凭据进行身份验证。

我的clientAuth中间件:



const firebase = require('firebase-admin');

const db = require('../db');

module.exports = async (req, res, next) => {
  try {
    const tokenId = req.get('Authorization').split('Bearer ')[1];
    console.log(tokenId) //yay, token
    const validToken = await firebase.auth().verifyIdToken(tokenId);
    console.log(validToken.uid) //error

    return (validToken && validTeam) ? next() : res.status(401).end();   
  } catch (e) {
    res.status(401).end();
  }
};




我得到的错误是“解码Firebase ID令牌失败”。确保传递了代表ID令牌的整个字符串JWT。'我该如何验证/解码此令牌?

1 个答案:

答案 0 :(得分:0)

我认为这可能不错,请使用谷歌复制此功能

const admin = require('firebase-admin')
exports.validateFirebaseIdToken = async (req, res, next) => {
    console.log('Check if request is authorized with Firebase ID token');

    if ((!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) &&
        !(req.cookies && req.cookies.__session)) {
        console.error('No Firebase ID token was passed as a Bearer token in the Authorization header.',
            'Make sure you authorize your request by providing the following HTTP header:',
            'Authorization: Bearer <Firebase ID Token>',
            'or by passing a "__session" cookie.');
        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];
    } else if (req.cookies) {
        console.log('Found "__session" cookie');
        // Read the ID Token from cookie.
        idToken = req.cookies.__session;
    } else {
        // No cookie
        res.status(403).send('Unauthorized');
        return;
    }


    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;
    }
};