DRF (Django Rest Framework) 验证 Google 令牌

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

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(
            &quot;https://www.googleapis.com/oauth2/v3/tokeninfo&quot;,
            params={&quot;id_token&quot;: self.token},
        )
        r.raise_for_status()

    def get_decoded_data(self):
        try:
            self.validate_token()
        except Exception:
            error = {&quot;message&quot;: &quot;Google token invalid.&quot;}
            raise ValidationError(error)
        else:
            data = jwt.decode(self.token, options={&quot;verify_signature&quot;: False})
            return {
                &quot;username&quot;: data[&quot;sub&quot;],
                &quot;email&quot;: data[&quot;email&quot;],
                &quot;name&quot;: data.get(&quot;name&quot;),
                &quot;provider&quot;: &quot;google&quot;,
            }

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

确定