📅  最后修改于: 2023-12-03 15:23:34.926000             🧑  作者: Mango
如果您使用 Google 登录来调用您的 API 或身份验证用户,则通常需要交换用户的 Google 身份验证令牌(idToken)来验证用户是否经过身份验证,并在您的保护 API 中充当凭据。
在没有 Firebase 的情况下,您可以使用 Google API 客户端库来验证 idToken。
pip install google-auth
from google.oauth2 import id_token
from google.auth.transport.requests import Request
def get_verified_user_id_token(token):
try:
# Verify and return the ID Token from the token string
idinfo = id_token.verify_oauth2_token(
token, Request())
if 'accounts.google.com' in idinfo['iss']:
return idinfo
else:
raise ValueError('Wrong issuer.')
except ValueError as e:
# Invalid input or Google API server error
raise ValueError('Failed to validate ID Token: {0}'.format(str(e)))
def my_api_endpoint(token):
try:
valid_token = get_verified_user_id_token(token)
# Do something with the valid_token, such as get the user_id
# user_id = valid_token['sub']
return 'Valid token!', 200
except ValueError as e:
return str(e), 400
使用这个代码块,您可以在没有 Firebase 的情况下颤动谷歌登录的 idToken 了。
这是一个通过 Google API 客户端库在没有 Firebase 的情况下验证 Google 登录 idToken 的示例。请注意,此代码块仅适用于 Python。如果您使用任何其他编程语言,请参考适当的 Google API 客户端库文档。