Skip to content

Instantly share code, notes, and snippets.

@yukirin
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukirin/4da415d9e7cb75a6a66d to your computer and use it in GitHub Desktop.
Save yukirin/4da415d9e7cb75a6a66d to your computer and use it in GitHub Desktop.
Python3系でOpen ID ConnectのID Token(JWT)検証
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ssl import PEM_cert_to_DER_cert
import jwt
import requests
from Crypto.Util.asn1 import DerSequence
from Crypto.PublicKey import RSA
class GoogleIdToken:
_GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs'
_GOOGLE_ISS_URI = 'accounts.google.com'
def __init__(self, jwt):
self._jwt = jwt
self.token = None
def is_valid(self, aud, iss=_GOOGLE_ISS_URI):
for pem in self._get_certs().values():
try:
token = jwt.decode(self._jwt, key=self._get_pubkey(pem))
except (jwt.DecodeError, jwt.ExpiredSignature): pass
else:
if token['aud'] == aud and token['iss'] == iss:
self.token = token
return True
return False
def _get_certs(self):
certs = requests.get(GoogleIdToken._GOOGLE_CERTS_URI)
if certs.status_code == 200: return certs.json()
return {}
def _get_pubkey(self, pem):
der = PEM_cert_to_DER_cert(pem)
cert = DerSequence()
cert.decode(der)
tbs_cert = DerSequence()
tbs_cert.decode(cert[0]) # TBSCertiFicate
pubkey_info = tbs_cert[6] # SubjectPublicKeyInfo
return RSA.importKey(pubkey_info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment