Skip to content

Commit d896ab3

Browse files
feat(auth): verify id token
This method decodes the claims associated with the user in his id token. closes #9
1 parent a428aec commit d896ab3

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

firebase/auth/__init__.py

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@
1818
import random
1919
import datetime
2020
import python_jwt as jwt
21-
import jwcrypto.jwk as jwk
2221
from hashlib import sha256
22+
from jwcrypto.jwk import JWK
2323
from urllib.parse import parse_qs
2424
from google.auth.transport.requests import Request
2525
from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat
@@ -209,7 +209,7 @@ def create_custom_token(self, uid, additional_claims=None, expiry_minutes=60):
209209
"""
210210

211211
service_account_email = self.credentials.service_account_email
212-
private_key = jwk.JWK.from_pem(self.credentials.signer._key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()))
212+
private_key = JWK.from_pem(self.credentials.signer._key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()))
213213

214214
payload = {
215215
"iss": service_account_email,
@@ -587,6 +587,32 @@ def set_custom_user_claims(self, user_id, custom_claims):
587587

588588
raise_detailed_error(request_object)
589589

590+
def verify_id_token(self, id_token):
591+
""" Decode Firebase Auth ID token.
592+
593+
| For more details:
594+
| `Firebase Authentication | Verify ID tokens using a third-party JWT library`_
595+
596+
.. _Firebase Authentication | Verify ID tokens using a third-party JWT library: https://firebase.google.com/docs/auth/admin/verify-id-tokens#verify_id_tokens_using_a_third-party_jwt_library
597+
598+
:type id_token: str
599+
:param id_token: A Firebase Auth ID token for the user.
600+
601+
:return: Decoded claims of Firebase Auth ID token.
602+
:rtype: dict
603+
"""
604+
605+
header, _ = jwt.process_jwt(id_token)
606+
607+
response = self.requests.get('https://www.googleapis.com/robot/v1/metadata/x509/[email protected]')
608+
609+
pub_pem = response.json()[header['kid']]
610+
611+
pub_key = JWK.from_pem(bytes(pub_pem.encode('utf-8')))
612+
_, claims = jwt.verify_jwt(id_token, pub_key, [header['alg']], checks_optional=True)
613+
614+
return claims
615+
590616

591617
def _load_client_secret(secret):
592618
""" Load social providers' client secret from file if file path

0 commit comments

Comments
 (0)