DRF (Django Rest Framework) 验证 Google 令牌

huangapple go评论78阅读模式
英文:

DRF (Django Rest Framework) verify google token

问题

我需要在我的后端 Django Rest Framework 中验证 Google 令牌。我使用 React 库 reactjs-social-login,它完美工作并发送数据:

然后,我将这些数据发送到 APIView。我安装了 Django 的 google-auth 库。问题是,我如何检查此 Google 访问令牌的验证。该库期望另一个令牌:

  1. def verify_token(
  2. id_token,
  3. request,
  4. audience=None,
  5. certs_url=_GOOGLE_OAUTH2_CERTS_URL,
  6. clock_skew_in_seconds=0,
  7. ):

在这种情况下,我遇到了异常。我的视图:

  1. try:
  2. id_token.verify_oauth2_token(google_user['token'], requests.Request())
  3. except ValueError:
  4. 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:

  1. {
  2. "access_token": "...",
  3. "token_type": "Bearer",
  4. "expires_in": 3599,
  5. "scope": "...",
  6. "authuser": "0",
  7. "prompt": "none",
  8. "sub": "...",
  9. "name": "...",
  10. "given_name": "...",
  11. "family_name": "...",
  12. "picture": "...",
  13. "email": "...",
  14. "email_verified": true,
  15. "locale": "en"
  16. }

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:

  1. def verify_token(
  2. id_token,
  3. request,
  4. audience=None,
  5. certs_url=_GOOGLE_OAUTH2_CERTS_URL,
  6. clock_skew_in_seconds=0,
  7. ):

And in this case I've got the exception. My view:

  1. try:
  2. id_token.verify_oauth2_token(google_user['token'], requests.Request())
  3. except ValueError:
  4. 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 -->

  1. import jwt
  2. import requests
  3. from rest_framework.serializers import ValidationError
  4. class GoogleAuthProvider:
  5. def __init__(self, token):
  6. self.token = token
  7. def validate_token(self):
  8. r = requests.get(
  9. &quot;https://www.googleapis.com/oauth2/v3/tokeninfo&quot;,
  10. params={&quot;id_token&quot;: self.token},
  11. )
  12. r.raise_for_status()
  13. def get_decoded_data(self):
  14. try:
  15. self.validate_token()
  16. except Exception:
  17. error = {&quot;message&quot;: &quot;Google token invalid.&quot;}
  18. raise ValidationError(error)
  19. else:
  20. data = jwt.decode(self.token, options={&quot;verify_signature&quot;: False})
  21. return {
  22. &quot;username&quot;: data[&quot;sub&quot;],
  23. &quot;email&quot;: data[&quot;email&quot;],
  24. &quot;name&quot;: data.get(&quot;name&quot;),
  25. &quot;provider&quot;: &quot;google&quot;,
  26. }

<!-- 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.

huangapple
  • 本文由 发表于 2023年2月24日 15:09:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定