英文:
DRF (Django Rest Framework) verify google token
问题
我需要在我的后端 Django Rest Framework 中验证 Google 令牌。我使用 React 库 reactjs-social-login,它完美工作并发送数据:
然后,我将这些数据发送到 APIView。我安装了 Django 的 google-auth 库。问题是,我如何检查此 Google 访问令牌的验证。该库期望另一个令牌:
def verify_token(
id_token,
request,
audience=None,
certs_url=_GOOGLE_OAUTH2_CERTS_URL,
clock_skew_in_seconds=0,
):
在这种情况下,我遇到了异常。我的视图:
try:
id_token.verify_oauth2_token(google_user['token'], requests.Request())
except ValueError:
raise AuthenticationFailed(code=403, detail="Bad token Google")
感谢任何建议。
英文:
I need to verify google token in my backend drf. I use React library reactjs-social-login, and it works perfect and send data:
{
"access_token": "...",
"token_type": "Bearer",
"expires_in": 3599,
"scope": "...",
"authuser": "0",
"prompt": "none",
"sub": "...",
"name": "...",
"given_name": "...",
"family_name": "...",
"picture": "...",
"email": "...",
"email_verified": true,
"locale": "en"
}
Then I send this data to APIView. I install google-auth library for django. The question is, how can I check validation of this google access token. Library expect another token:
def verify_token(
id_token,
request,
audience=None,
certs_url=_GOOGLE_OAUTH2_CERTS_URL,
clock_skew_in_seconds=0,
):
And in this case I've got the exception. My view:
try:
id_token.verify_oauth2_token(google_user['token'], requests.Request())
except ValueError:
raise AuthenticationFailed(code=403, detail="Bad token Google")
Thanks for any advices
答案1
得分: 0
这部分内容是关于使用Python编写的一个类,用于验证和解码Google令牌以获取用户信息。你可以创建一个GoogleAuthProvider
的实例,并在初始化时传递id_token
,然后调用get_decoded_data()
方法来获取id_token
中的信息。
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
import jwt
import requests
from rest_framework.serializers import ValidationError
class GoogleAuthProvider:
def __init__(self, token):
self.token = token
def validate_token(self):
r = requests.get(
"https://www.googleapis.com/oauth2/v3/tokeninfo",
params={"id_token": self.token},
)
r.raise_for_status()
def get_decoded_data(self):
try:
self.validate_token()
except Exception:
error = {"message": "Google token invalid."}
raise ValidationError(error)
else:
data = jwt.decode(self.token, options={"verify_signature": False})
return {
"username": data["sub"],
"email": data["email"],
"name": data.get("name"),
"provider": "google",
}
<!-- end snippet -->
Basically, create an instance of GoogleAuthProvider
and pass the id_token
in init.
Then call get_decoded_data()
to get info from that id_token
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论