firebase-admin (nodejs) cannot verify auth token (JWT)

最后都变了- 提交于 2021-01-29 18:29:09

问题


I am using firebase-admin (node-js) to verify Auth token.

I am using the sample provided by firebase docs

I have tried to decode the token I am using, and it works

{
 "iss": "https://securetoken.google.com/xxxxxx",
 "aud": "xxxxxxx",
 "auth_time": 1557423742,
 "user_id": "xxxxxxxxxxxxx",
 "sub": "xxxxxxxxx",
 "iat": 1557427419,
 "exp": 1557431019,
 "email": "xxxxx@gmail.com",
 "email_verified": false,
 "firebase": {
  "identities": {
   "email": [
    "xxxxx@gmail.com"
   ]
  },
  "sign_in_provider": "password"
 }
}

I have tried logging the token inside firebase-admin code

lib/auth/token-verifier.js

   FirebaseTokenVerifier.prototype.verifyJWT = function (jwtToken) {
        var _this = this;
        console.log(`"${jwtToken}"`); // HERE
        if (!validator.isString(jwtToken)) {
            throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, "First argument to " + this.tokenInfo.verifyApiName + " must be a " + this.tokenInfo.jwtName + " string.");
        }
        if (!validator.isNonEmptyString(this.projectId)) {
            throw new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_CREDENTIAL, "Must initialize app with a cert credential or set your Firebase project ID as the " +
                ("GOOGLE_CLOUD_PROJECT environment variable to call " + this.tokenInfo.verifyApiName + "."));
        }
        var fullDecodedToken = jwt.decode(jwtToken, {
            complete: true,
        });
        var header = fullDecodedToken && fullDecodedToken.header;
        var payload = fullDecodedToken && fullDecodedToken.payload;
        var projectIdMatchMessage = " Make sure the " + this.tokenInfo.shortName + " comes from the same " +
            "Firebase project as the service account used to authenticate this SDK.";
        var verifyJwtTokenDocsMessage = " See " + this.tokenInfo.url + " " +
            ("for details on how to retrieve " + this.shortNameArticle + " " + this.tokenInfo.shortName + ".");
        var errorMessage;
        if (!fullDecodedToken) {
            errorMessage = "Decoding " + this.tokenInfo.jwtName + " failed. Make sure you passed the entire string JWT " +
                ("which represents " + this.shortNameArticle + " " + this.tokenInfo.shortName + ".") + verifyJwtTokenDocsMessage;
        }
        else if (typeof header.kid === 'undefined') {
            var isCustomToken = (payload.aud === FIREBASE_AUDIENCE);
            var isLegacyCustomToken = (header.alg === 'HS256' && payload.v === 0 && 'd' in payload && 'uid' in payload.d);
            if (isCustomToken) {
                errorMessage = this.tokenInfo.verifyApiName + " expects " + this.shortNameArticle + " " +
                    (this.tokenInfo.shortName + ", but was given a custom token.");
            }
            else if (isLegacyCustomToken) {
                errorMessage = this.tokenInfo.verifyApiName + " expects " + this.shortNameArticle + " " +
                    (this.tokenInfo.shortName + ", but was given a legacy custom token.");
            }
            else {
                errorMessage = 'Firebase ID token has no "kid" claim.';
            }
            errorMessage += verifyJwtTokenDocsMessage;
        }
        else if (header.alg !== this.algorithm) {
            errorMessage = this.tokenInfo.jwtName + " has incorrect algorithm. Expected \"" + this.algorithm + "\" but got " +
                "\"" + header.alg + "\"." + verifyJwtTokenDocsMessage;
        }
        else if (payload.aud !== this.projectId) {
            errorMessage = this.tokenInfo.jwtName + " has incorrect \"aud\" (audience) claim. Expected \"" +
                this.projectId + "\" but got \"" + payload.aud + "\"." + projectIdMatchMessage +
                verifyJwtTokenDocsMessage;
        }
        else if (payload.iss !== this.issuer + this.projectId) {
            errorMessage = this.tokenInfo.jwtName + " has incorrect \"iss\" (issuer) claim. Expected " +
                ("\"" + this.issuer + "\"") + this.projectId + "\" but got \"" +
                payload.iss + "\"." + projectIdMatchMessage + verifyJwtTokenDocsMessage;
        }
        else if (typeof payload.sub !== 'string') {
            errorMessage = this.tokenInfo.jwtName + " has no \"sub\" (subject) claim." + verifyJwtTokenDocsMessage;
        }
        else if (payload.sub === '') {
            errorMessage = this.tokenInfo.jwtName + " has an empty string \"sub\" (subject) claim." + verifyJwtTokenDocsMessage;
        }
        else if (payload.sub.length > 128) {
            errorMessage = this.tokenInfo.jwtName + " has \"sub\" (subject) claim longer than 128 characters." +
                verifyJwtTokenDocsMessage;
        }
        if (typeof errorMessage !== 'undefined') {
            return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, errorMessage));
        }
        return this.fetchPublicKeys().then(function (publicKeys) {
            if (!publicKeys.hasOwnProperty(header.kid)) {
                return Promise.reject(new error_1.FirebaseAuthError(error_1.AuthClientErrorCode.INVALID_ARGUMENT, _this.tokenInfo.jwtName + " has \"kid\" claim which does not correspond to a known public key. " +
                    ("Most likely the " + _this.tokenInfo.shortName + " is expired, so get a fresh token from your ") +
                    "client app and try again."));
            }
            else {
                return _this.verifyJwtSignatureWithKey(jwtToken, publicKeys[header.kid]);
            }
        });
    };
const admin = require('firebase-admin');
var serviceAccount = require('./firebase-adminsdk-file.json');

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "{{ databaseURL }}"
});

const idToken = `{{ token }}`;

admin.auth()
    .verifyIdToken(idToken)
    .then((user) => {
        console.log(user.uid)
    }).catch((reason) => {
        console.log(reason)
    });

I expect the output to be a valid user id

but I get this error:

   { code: 'auth/argument-error',
     message:
      '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.' },
  codePrefix: 'auth' }

firebase-admin version:

"firebase-admin": "^7.3.0"

UPDATE When I add this line, it works

let idToken = `{{ token }}`;
idToken = idToken.split(":")[0];

Do I have to remove last part of auth token?

":AIzaSyA13xxxxxxxxxx"

来源:https://stackoverflow.com/questions/56090338/firebase-admin-nodejs-cannot-verify-auth-token-jwt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!