Search code examples
node.jsfirebasefirebase-authenticationjwtfirebase-admin

How to decode custom token generated using firebase admin NodeJS sdk


I am using firebase nodejs admin sdk to generate a custom token that is later sent to android client. I have been successful with generating the token using admin.auth().createCustomToken(). However, I need to decode this token to get the uid and other custom claims that was set when generating the token.

I have searched and it seems firebase do not have an out of the box solution using it's admin sdk to decode the custom token (Correct me if i'm wrong).

The solution I have found is using signInWithCustomToken() to first get the idToken and then using firebase's admin sdk verifyIdToken method to get the uid. I'm a bit skeptical about this solution as I don't think it can provide access to the custom claims I set originally.

The other solution I've found is using jwt nodejs module to decode this token. However, jwt requires an API key to decode this token. Not sure about the API key since I used a service account to generate the token in the first place.

Now the questions:

  1. How best can I decode this token in nodejs?
  2. Do the admin sdk for firebase not have any built in method to decode this token directly just as it was able to create the token?

Edit As Doug has pointed, the reason I need to decode the token is to get the uid (string) and an additional claim which has the user_id (int) associated with a postgres users table that was set during signup. These ids are used to authorise certain http requests

Also I happen to append the custom token as a query parameter to a password reset link. Hence I need to decode the token to know which user owns it.


Solution

  • Found a fix. I used id tokens. After I signed in using signInWithCustomToken with firebase android sdk, the sdk actually generates an id token. The id token rather than the custom token should be sent to the server on http request. By using the admin.auth().verifyIdToken(idToken) method in the firebase admin nodejs environment (on the server), we are able to decode the token to get both the uid and custom claims originally set. The decoded token looks like this:

    {
    "is_id_verified": false,
    "id": 4,
    "iss": "https://securetoken.google.com/my-app-name",
    "aud": "my-app-name",
    "auth_time": 1628738368,
    "user_id": "email@gmail.com",
    "sub": "email@gmail.com",
    "iat": 1628738369,
    "exp": 1628741969,
    "firebase": {
        "identities": {},
        "sign_in_provider": "custom"
    },
    "uid": "email@gmail.com"
    

    }