android - 在对 Python 的 Android 后端调用中验证 Id token

标签 android python-3.x google-oauth google-api-client google-api-python-client

如解释here ,我正在尝试验证由 Android 应用程序传递到运行 python3 的服务器的 token 。

我想验证传递的 token 。问题是我在 google-api-python-client 库不支持的服务器上运行 python3。我从这个 site 中使用 pyjwt 和 requests 库找到了以下解决方法:

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):
        cert = requests.get(GOOGLE_CERTS_URI)
        if cert.status_code == 200:
            return json.loads(cert.content)

    def isValid(self, token, audience, clientId=None):
        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

我的两个问题是:

  1. 有谁知道可以在 python3 中使用的不同和/或更好的现有解决方案吗?
  2. 上面的解决方案是否完整?

最佳答案

经过几个小时的谷歌搜索和反复试验后,这就是我最终的做法。

依赖关系

pip install cryptography PyJWT requests

代码

import jwt, requests
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs'

def verify_id_token(id_token, audience):
    certs = requests.get(GOOGLE_CERTS_URI).json()

    for cert in certs.values():
        cert = str.encode(cert)
        cert_obj = load_pem_x509_certificate(cert, default_backend())
        pub_key = cert_obj.public_key()
        try:
            return jwt.decode(id_token, pub_key, algorithm='RS256',
                              audience=audience)
        except (jwt.exceptions.DecodeError,
                jwt.exceptions.ExpiredSignatureError) as e:
            pass

编辑

我刚刚意识到 Google provides an example在 python 中,使用他们的 oauth2client图书馆。

关于android - 在对 Python 的 Android 后端调用中验证 Id token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397082/

相关文章:

node.js - 如何从 passportjs 中的刷新 token 获取新的 Google oauth 访问 token

java - gridview 重复显示同一张图片

Android ListView ItemClickListener 无法与 Horizo​​ntalScrollView 一起正常工作

Python Enum 在对成员值使用相同的字典时显示奇怪的行为

python - 列表理解中的多个操作

python - matplotlib 中的 set_xlim() 和 set_ylim() 是什么?

android - Unity 3D 插件的 Google Drive 授权错误

javascript - Google oauth2.0 与组织的网络应用程序?

android - Android 中的媒体播放器内存管理?

android - 使用 svn :external 将 Android 库添加到项目中