Verify Firebase Google Auth ID Tokens with Any JWT Library
In Firebase authentication, it's common to use Firebase Admin SDK to verify ID tokens. However, there are scenarios where you might want to handle the verification process manually, allowing you to perform custom handling of expired tokens and other checks. This post will guide you through verifying Firebase Google Auth ID tokens using any JWT library and demonstrate how to handle expired tokens.
Why Manual Verification?
By default, Firebase's admin.auth().verifyIdToken()
method throws an exception when the ID token has expired, which can limit your ability to handle the expired token gracefully. In some cases, you might want to extract information from an expired token or implement custom logic.
Prerequisites
Before we start, make sure you have the necessary libraries and dependencies installed:
- Node.js
- Your JWT library of choice (e.g.,
jsonwebtoken
) - A Firebase project and access to Firebase Admin SDK
Setting Up the JWT Verification
Import the libraries
First you need to import the jsonwebtoken
and node-fetch
libraries.
const jwt = require('jsonwebtoken');
const fetch = require('node-fetch');
Fetch Google Public Signing keys.
When verifying Firebase ID tokens, it's crucial to utilize Google's publicly accessible signing keys, which are updated regularly, typically rotating every few hours. These keys can be obtained from Firebase's official endpoint at https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com. This endpoint provides a JSON dictionary format containing keys associated with unique identifiers, known as "kid." These "kid" values correspond to the specific keys used for signing the ID token JWTs. By matching the "kid" field from the token's header with the relevant key from the fetched certificates, you can ensure the integrity and authenticity of the token's signature. This meticulous process is a vital aspect of ID token verification in Firebase, enhancing the security and trustworthiness of your authentication system. For comprehensive details and guidelines on server-side ID token validation, please refer to the official Firebase documentation.
async function fetchGooglePublicKeys() {
let response = undefined;
response = await fetch('https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com');
if (response !== undefined && response.status !== undefined
&& response.status === 200) {
return await response.json();
}
return undefined;
}
You can print the keys to learn about the format structure.
Verify the JWT with the Signature validation
The following code is designed to provide a more flexible approach for verifying Firebase Google Auth ID tokens, offering the ability to handle expired tokens and customize the verification process with care and precision.