I've searched for any real examples that take a token from a firebase session and actually verify it. I saw some examples using python-jose, but wanted a working example using python_jwt. There's a lot of examples that decode it, but none that I saw with a end-to-end verification example
Asked
Active
Viewed 819 times
2
-
Hi there, welcome to SO! Please take your time to familiarize yourself with the site by taking [the tour](https://stackoverflow.com/tour), reading up on [How to Ask](https://stackoverflow.com/help/how-to-ask), going through [this brilliant question checklist](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), and lastly, understanding how to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Additionally, your question lacks your attempt. Hope this helps. – Jon Jaussi Dec 22 '18 at 18:55
1 Answers
3
I tried this using python-jwt package and jwcrypto in Ubuntu, but they are too old. I removed the ubuntu packages, and did:
sudo pip install python_jwt
sudo pip install jwcrypto
I wrote the following function to validate the token:
import python_jwt as jwt
import urllib, json
import jwcrypto.jwk as jwk
class UnknownKID(Exception):
pass
def validate_token(token):
certificate_url = 'https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com'
response = urllib.urlopen(certificate_url)
certs = response.read()
certs = json.loads(certs)
processed_token = jwt.process_jwt(token)
kid = processed_token[0]['kid']
if kid not in certs:
raise UnknownKID
pub = jwk.JWK.from_pem(str(certs[kid]))
return jwt.verify_jwt(token, pub_key=pub, allowed_algs=[processed_token[0]['alg']], checks_optional=True)
Hopefully useful to someone else.

Terry Hardie
- 101
- 1
- 4