Google OAuth2 and Django Rest Auth

Gonzalo Martinez
1 min readFeb 15, 2019

DISCLAIMER: This works for me in that time but maybe now you can install a new version or check this post from the original authors. https://github.com/pennersr/django-allauth/issues/2443#issuecomment-582999543

After checking and reading a lot of issues, and explanations I found some that fits to my needs.

First of all you need to install google-api-python-client https://developers.google.com/api-client-library/python/start/installation

$ pip install --upgrade google-api-python-client

Then you need to add a subclass to GoogleOAuth2Adapter and use some of the Google Recommendations https://developers.google.com/identity/sign-in/web/backend-auth to verify the token.

and you need to modify the ./env/lib/python3.7/site-packages/allauth/socialaccount/providers/google/provider.py

def extract_uid(self, data):
return str(data['id'])

to this

def extract_uid(self, data):
return str(data['sub'])

This is because the id_token use the sub field to store the id info

Then you can follow the recomendations of django rest auth add the GoogleLoginView.

from .googleviews import GoogleOAuth2AdapterIdToken # import custom adapter
from rest_auth.registration.views import SocialLoginView
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2AdapterIdToken
client_class = OAuth2Client

Finally the url

from accounts.views import GoogleLoginurlpatterns =+ path(‘rest-auth/google/’, GoogleLogin.as_view(), name=’goggle_login’)

And pass the id_token in POST request in the access_token field and if you configured the Social apps with the same ClientID and Secret that you Javascript everything works like a charm.

I expect that this is useful for someone.

--

--

Gonzalo Martinez

Integration Manager at NCR, SysAdmin, Python Developer, Elixir Hobbist, making things work.