/EDIT: Updated to check the audience and optionally clientid
Google’s Tim Bray recently published an excellent article (here) on using the new Google Play Services APIs to authenticate requests from Android devices using the Google account on the device.
The article contained Java, Ruby and PHP examples for the server side but unfortunately no python so here is my extremely naive implementation but it should be enough to give you a leg up.
It requires requests and PyJWT
import json
import jwt
import requests
GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs'
class GoogleIdToken(object):
def __init__(self):
self._certs = {}
self._token = {}
def getCerts(self):
"""
Grab the certificats from Google to decrypt the JWT token
This really should cache the certs
"""
cert = requests.get(GOOGLE_CERTS_URI)
if cert.status_code == 200:
return json.loads(cert.content)
def isValid(self, token, audience, clientId=None):
"""
Try each key in turn until we find one that decrypts the token
"""
self._certs = self.getCerts()
for key in self._certs:
try:
token = jwt.decode(token, key=self._certs[key], verify=False)
if 'email' in token and 'aud' in token:
if token['aud'] == audience and (clientId == token['cid'] if clientId is not None else True):
self._token = token
return True
except Exception, e:
print "Error decoding: %s" % e.message
return False