Anna Berezko
Anna Berezko

Reputation: 95

DRF (Django Rest Framework) verify google token

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

Upvotes: 0

Views: 654

Answers (1)

Saiful Azad
Saiful Azad

Reputation: 1941

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",
            }
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.

Upvotes: 0

Related Questions