Django rest framework and Social Logins with python-social-auth

Shrinidhi N Hegde
2 min readJun 8, 2021

--

When I looked for some help on the title, I found rest-social-auth and django-rest-framework-social-oauth2. While I did try to use these packages individually to achieve my goal, for some reason, I found myself struggling with the documentation or the package not working with the type of authentication I wanted to use in my project. I figured there was a way to do it without any of these packages, but there was little to no information about it on the internet which brings me here to shed some light on the same.

Pre-requisites:

You need to have Django-rest-framework (DRF) and social-auth-app-django installed and configured in your project. If you haven’t already, feel free to click on the respective links and help yourselves… I have included links to very easy tutorials.

Once you have done that, you are just a step away from the solution.

Social Login with DRF:

So simply we need to create a view and a URL route:

urls.py :

urlpatterns = [
path('social-login/<str:backend>/', views.SocialLogin, name='social-login') # backend is the social_provider
]

views.py :

from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.contrib.auth import login
from social_django.utils import psa
@api_view(['POST'])
@psa('social:complete')
@permission_classes((permissions.AllowAny,))
def SocialLogin(request, backend):
token = request.data['accessToken']

user = request.backend.do_auth(token)
if user:
# your user is created
# do anything here for eg:
# login the user and return an auth token
login(request, user)
return Response({
'token': AuthToken.objects.create(user)[1],
'user_first_name': user.first_name
})
else:
return Response(status=500)

So you can make a POST request to the URL route with:
‘backend’ in the URL and the ‘accessToken’ in the request body.

‘backend’ is the social_provider. Eg: ‘github’, ‘google-oauth2’, etc.
and ‘accessToken’ is the token obtained by the social_provider.

Obtaining the accessToken:

There are various ways to obtain the accessToken from your provider. I would advise you to go through the documentation provided by your social-provider on how to obtain the accessToken.

For example, if you’re using React with django backend and trying to login via Facebook, you can use this npm package to obtain the accessToken. You can now pass the obtained accessToken to the Django URL we just created and it will create a user for you.

Thank you for reading this. Cheers!

--

--

No responses yet