Firebase Token Verification

2020-04-08 07:41发布

问题:

I have a PHP backend and an Android client. With the client the users can log into my app using either Google or Facebook, both via Firebase. I get the token from the FirebaseUser and send it to my server. It is straightforward that the first section (the header) contains the algorithm (which is RS256) and the second one (the payload) has all the user related data. There's a third section which is the signature of the first two to enable verification on my backend. The problem is, I don't know how to do that. More specifically with what.

I used JWT.io to check my token and tried to verify it with no luck. Since the algorithm used is RS256, the verification should be done via the public key. But what public key? I tried with my app's keystore, tried it with Google's certs, but it just keeps saying it's invalid. I understand that the header's kid field is the signing key's ID and I should look for it, but I don't know where.

The Firebase docs don't help either. There is a guide about ID token verification, but that's just useless because it's Java / Node.JS and it still doesn't say anything about public keys.

So the question is: where do I get the public keys from?

回答1:

Okay, so I dug into the source of the Firebase Server SDK and found the location of the public keys: https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com

Don't really know why they just couldn't put it on their website...

Anyways, I'm not sure, but I guess that these keys change on a daily basis (just like the OAuth2 keys do), so you must check and re-cache them on your server every now and then.

Also, you have to check the following values:

  • alg == "RS256"
  • iss: https://securetoken.google.com/<firebaseProjectID>
  • aud: <firebaseProjectID>
  • sub is non-empty

Found these at this similar question (just scroll to the bottom of the answer), which was found by searching for that specific googleapis.com URL.