我有一个 React Native Android 应用程序,它使用 Google Sign-In 来获取用户个人资料和电子邮件信息并生成 ID token (使用 https://github.com/react-native-community/google-signin )。登录成功,我正在应用程序上显示用户名、电子邮件、照片等。
然后,我尝试将 ID token 发送到 Django + DRF 后端,以便对其进行验证并创建和/或登录相关的用户帐户。我按照此处的说明进行操作:https://developers.google.com/identity/sign-in/web/backend-auth
这是我的端点代码。现在我只是复制应用程序生成的 ID token 并通过 Postman 将其发送到后端。
class GoogleView(APIView):
def post(self, request):
token = {'idToken': request.data.get('idToken')}
print(token)
try:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), MY_APP_CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError:
# Invalid token
content = {'message': 'Invalid token'}
return Response(content)
当我发送 POST 请求时,第一个打印语句将运行,确认 token 已正确接收。然而,第二个打印语句永远不会运行,我总是得到“无效 token ”响应。因此,我相信 verify_oauth2_token 不知何故失败了,但它没有给我更多信息。
我以前从未使用过 Google 登录,因此我完全有可能错过了一些明显的事情。将不胜感激任何帮助!
最佳答案
在 friend 的帮助下自己解决了这个问题。只需更改异常处理以显示相关错误,然后传递 token['id_token'] 而不是完整的 token 字典。新代码:
class GoogleView(APIView):
def post(self, request):
token = {'id_token': request.data.get('id_token')}
print(token)
try:
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token['id_token'], requests.Request(), MY_APP_CLIENT_ID)
print(idinfo)
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
return Response(idinfo)
except ValueError as err:
# Invalid token
print(err)
content = {'message': 'Invalid token'}
return Response(content)
关于python - 在 Django 中验证 Google ID token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61187305/