调用Google Client API verify_oauth2_token时模块安装报错,求正确Python模块
谷歌官方文档指出,调用verify_oauth2_token API验证Google ID令牌时,需使用Python的google.oauth2和google.auth.transport模块,示例代码如下:
from google.oauth2 import id_token from google.auth.transport import requests # (Receive token by HTTPS POST) # ... def test(): try: # Specify the CLIENT_ID of the app that accesses the backend: idinfo = id_token.verify_oauth2_token("token", requests.Request(), "CLIENT_ID") # Or, if multiple clients access the backend server: # idinfo = id_token.verify_oauth2_token(token, requests.Request()) # if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]: # raise ValueError('Could not verify audience.') # If auth request is from a G Suite domain: # if idinfo['hd'] != GSUITE_DOMAIN_NAME: # raise ValueError('Wrong hosted domain.') # ID token is valid. Get the user's Google Account ID from the decoded token. userid = idinfo['sub'] print("hello") except ValueError: # Invalid token print("fail") pass if __name__ == '__main__': test()
但在安装依赖时,无论是直接引用这些模块还是写入requirements.txt,都会出现如下报错:
ERROR: Could not find a version that satisfies the requirement google.oauth2 (from versions: none)
ERROR: No matching distribution found for google.oauth2
引用google.auth.transport时也会出现相同的找不到版本的报错。现咨询:这些模块是否受支持?若不支持,应使用哪些替代模块来实现verify_oauth2_token API的调用?
这些模块是受官方支持的,你只是搞错了安装方式——google.oauth2和google.auth.transport并不是独立的PyPI包,它们是google-auth这个官方认证库的子模块。
解决方法如下:
安装正确的依赖包
直接安装google-auth即可,执行命令:pip install google-auth或者在
requirements.txt中添加:google-auth>=2.0.0(指定最低版本可以避免兼容性问题)
代码无需修改
你提供的示例代码中的导入语句是完全正确的,安装google-auth后,from google.oauth2 import id_token和from google.auth.transport import requests就能正常工作。额外说明
如果你的代码需要使用谷歌官方的HTTP传输工具,可能还需要安装google-auth-httplib2,但你当前的示例代码使用的是标准的requests.Request(),所以仅安装google-auth就足够完成ID令牌的验证。
内容的提问来源于stack exchange,提问作者Steven Mueller

