Search code examples
djangodjango-rest-frameworkdjango-rest-auth

Django Rest Framework: How can I create endpoint for logging via Gmail (Google)?


I am trying to create API and I'm wondering how I can create an endpoint for authenticating via Gmail account. Seems like django-rest-auth supports only Facebook and Twitter.

Anyone could give me tips?


Solution

  • I am using Django rest auth in one of my projects and it does support Google sign-in. It supports all the social provider which django-allauth supports. Here is the list of the supported social provider by django-allauth and django-rest-auth

    # social_auth_view.py
    
    from rest_framework_jwt.authentication import JSONWebTokenAuthentication
    from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
    from rest_auth.registration.views import SocialLoginView
    
    class GoogleLogin(SocialLoginView):
        adapter_class = GoogleOAuth2Adapter
    
    # urls.py
    urlpatterns += [
        ...,
        url(r'^rest-auth/google/$', GoogleLogin.as_view(), name='google_login')
    ]
    

    So, If you want to support any other social provider.

    1. Import adapter for your social provider from allauth.socialaccount.providers.
    2. Create new view as a subclass of rest_auth.registration.views.SocialLoginView.
    3. Add the adapter imported in step 1 in the view as adapter_class attribute.
    4. Import this view in urls.py