验证Firebase ID令牌时出错:TypeError:无法读取未定义的属性“apply”

时间:2017-06-15 18:35:09

标签: javascript firebase google-cloud-functions firebase-admin

我正在尝试在Firebase功能部署中部署HTTP请求触发功能。我收到了这个错误,我不知道为什么。 idToken的解码成功

Error while verifying Firebase ID token: TypeError: Cannot read property 'apply' of undefined
    at /user_code/node_modules/express/lib/router/index.js:635:14
    at next (/user_code/node_modules/express/lib/router/index.js:260:14)
    at admin.auth.verifyIdToken.then.decodedIdToken (/user_code/index.js:24:9)
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

我的代码几乎是从样本中复制粘贴的:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const express = require('express');
const cors = require('cors')({origin: true});
const addDeviceToken = new express.Router();

const dbRef = admin.database().ref();

const validateFirebaseIdToken = (request, response, next) => {
    if (!request.headers.authorization || !request.headers.authorization.startsWith('Bearer ')) {
        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>');
        response.status(403).send("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.");
        return;
    }

    let idToken = request.headers.authorization.split('Bearer ')[1];

    admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
        request.user = decodedIdToken;
        next();
    }).catch(error => {
        console.error('Error while verifying Firebase ID token:', error);
        response.status(455).send('Unauthorized');
    })
};

addDeviceToken.use(cors);
addDeviceToken.use(validateFirebaseIdToken);
addDeviceToken.get('/addDeviceToken', (request, response) => {
    const uid = request.query.uid;
    const token = request.query.token;

    console.log(token);

    const tokensRef = dbRef.child("/users/" + uid + "/tokens");

    return tokensRef.once('value').then(function (snapshot) {
        let tokens = snapshot.val();
        if (tokens === null) tokens = {};

        if (!(token in tokens)) {
            tokens[token] = 1;
            tokensRef.set(tokens).then(() => {
                response.status(200).send("Token " + token + " saved.");
            });
            return;
        }

        response.status(200).send("The token " + token + " was already saved.");
    })
});

exports.addDeviceToken = functions.https.onRequest((req, res) => {
    if (!req.path) {
        req.url = `/${req.url}`
    }
    return addDeviceToken(req, res)
});

0 个答案:

没有答案