<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raj Mangal on Medium]]></title>
        <description><![CDATA[Stories by Raj Mangal on Medium]]></description>
        <link>https://medium.com/@rajmangal03?source=rss-cf3acb3d7eda------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JzKk3vAK_6rycpiB</url>
            <title>Stories by Raj Mangal on Medium</title>
            <link>https://medium.com/@rajmangal03?source=rss-cf3acb3d7eda------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajmangal03/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to implement OAuth in DRF in easy way]]></title>
            <link>https://rajmangal03.medium.com/how-to-implement-oauth-in-drf-in-easy-way-881a1508cb7b?source=rss-cf3acb3d7eda------2</link>
            <guid isPermaLink="false">https://medium.com/p/881a1508cb7b</guid>
            <category><![CDATA[django-allauth]]></category>
            <category><![CDATA[social-login]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <dc:creator><![CDATA[Raj Mangal]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 07:48:12 GMT</pubDate>
            <atom:updated>2026-03-09T12:51:16.003Z</atom:updated>
            <content:encoded><![CDATA[<p>In this Tech era, Authentication is a core part of modern web applications. Instead of creating accounts manually, users today expect to log in using services like Google, Microsoft, Facebook etc. This is made possible through a protocol called <strong>OAuth</strong>.</p><p>In this Blog we discuss about:</p><ul><li>What is OAuth ?</li><li>Why it important ?</li><li>How it works ?</li><li>How to implement it in Django ?</li><li>Problems which i faced during the implementation and how i solved them ?</li></ul><h3><strong>What is <em>OAuth</em> ?</strong></h3><p>OAuth(Open Authorization) is an Authorization protocal that allows users to log in to an application using a 3rd party provider without sharing their password. Instead of giving your information to any website manually, you authenticate once with a trusted provider (like Google) and that provider gives your basic info to the application.</p><p>if you want to learn more about OAuth <a href="https://medium.com/@yashvaishnav1404/authorization-or-authentication-using-oauth-2-0-part-1-429ae60a8fc6">click here</a></p><h3>Why it important ?</h3><p>When users had to create a separate account for every website, they faced several problems such as remembering passwords, security risks of password leaks, weak passwords, repeated registrations, etc. To solve these issues, <strong>Internet Engineering Task Force </strong>was developed a solution in <strong>April 2009,</strong> and it was named <strong>OAuth</strong>. In this approach, Authorized through a third party, which helped the application to get some non-sensitive data automatically. So, <strong>OAuth</strong> solved this by allowing a trusted identity provider.</p><h3>How it works ?</h3><p>Here, I consider Google as a Provider.</p><pre>User clicks Google login<br>        ↓<br>App redirects to Google<br>        ↓<br>User logs in on Google<br>        ↓<br>Google sends authorization code<br>        ↓<br>Backend exchanges code for user info<br>        ↓<br>User authenticated</pre><h3>How to implement it in Django ?</h3><p><strong>Firstly we need to create the space and install some dependencies:</strong></p><p>create directory and initiate the virtual environment then activate it.</p><pre>mkdir django_Oauth &amp;&amp; cd django_oauth<br><br>python3 -m venv venv<br><br>source venv/bin/activate</pre><p>now install the dependencies:</p><pre># I show you only oauth related libraries because i supposed you already <br># installed all required remaining libraries<br>pip install django-allauth dj-rest-auth python-dotenv requests cryptography</pre><p>after this create the file requirements.txt and write all these dependencies in this file for prevent the venv vulnerabilities.</p><pre>touch requirements.txt <br><br>pip freeze &gt;&gt; requirements.txt</pre><p>Now we are ready with our dependencies, so start our project:</p><pre>django-admin startproject django_oauth .</pre><p>also create an app named accounts to handle the users.</p><pre>python3 manage.py startapp accounts</pre><h3>Final implementation:</h3><p>The implementation below is the final working version after fixing several issues and debugging multiple errors. I’ll discuss those errors and solutions later in this article.</p><p>first we need to create a .env file to safe our secrets, write this code at your manage.py level:</p><pre>touch .env</pre><p>open this file and write some lines inside this file:</p><pre>SECRET = &quot;your_secret_key&quot;</pre><blockquote>here, dotenv is for environment variables which is used to safe the secrets from deploying in the production. we use os.getenv(‘variable_name’), here the variable name is stored in .env file and we import them.</blockquote><p>Now, its time to add some settings in settings.py(i write here my complete settings.py file’s ):</p><pre>import os<br>from datetime import timedelta<br>from dotenv import load_dotenv<br>load_dotenv()<br><br>SECRET_KEY = os.getenv(&quot;SECRET_KEY&quot;)<br># SECURITY WARNING: don&#39;t run with debug turned on in production!<br><br>INSTALLED_APPS = [<br>    &#39;django.contrib.sites&#39;,<br><br>    # rest_framework and jwt packages<br><br>    # OAuth<br>    &#39;allauth&#39;,<br>    &#39;allauth.account&#39;,<br>    &#39;allauth.socialaccount&#39;,<br>    &#39;allauth.socialaccount.providers.google&#39;,<br><br>    # api endpoints wrapper<br>    &#39;dj_rest_auth&#39;,<br><br>    # my apps<br>    &#39;accounts&#39;,<br>]<br>SITE_ID = 1<br><br>REST_FRAMEWORK = {<br>        # add here the authentication technique which you are using (mine: JWT)<br>}<br><br>SIMPLE_JWT = {<br># write here your simple jwt&#39;s setting<br>}<br><br>AUTHENTICATION_BACKENDS = [<br>    &quot;django.contrib.auth.backends.ModelBackend&quot;,<br>    &quot;allauth.account.auth_backends.AuthenticationBackend&quot;,<br>]<br><br># all-auth settings:<br># write here your allauth&#39;s settings, according to needs<br>...<br><br>MIDDLEWARE = [<br>    ...<br>    # add this middleware at the last index of middlewares<br>    &#39;allauth.account.middleware.AccountMiddleware&#39;,<br>]<br># add the social_account provider&#39;s details<br>SOCIALACCOUNT_PROVIDERS = {<br>    &quot;google&quot;:{<br>        &quot;APP&quot;:{<br>            &quot;client_id&quot;: os.getenv(&quot;GOOGLE_CLIENT_ID&quot;),<br>            &quot;secret&quot;: os.getenv(&quot;GOOGLE_CLIENT_SECRET&quot;),<br>            &quot;key&quot;:&quot;&quot;<br><br>        }<br>    }<br>}<br># specify login and logout urls for redirection<br>LOGIN_REDIRECT_URL = &quot;http://127.0.0.1:8000/api/google/success/&quot;<br>LOGOUT_REDIRECT_URL = &quot;http://127.0.0.1:8000/accounts/google/login/&quot;<br><br># specify your adapters&#39;s location<br>ACCOUNT_ADAPTER = &quot;accounts.adapters.AccountAdapter&quot;<br>SOCIALACCOUNT_ADAPTER = &quot;accounts.adapters.SocialAdapter&quot;</pre><p>here i store my sensitive content in .env file and delete from this file because these settings will go in the production.</p><p>These settings specifies how our social account provider works. For client_id and client_secret go through the <a href="https://console.cloud.google.com/">link</a>. Then click on the New Project (locates at the right of Google Cloud heading), then clicks on new project again, then fill the project name field and fill “no organization” in all remaining fields. Then on the overview page search “credentials” in the search field on top of the page, then create new credentials by clicking on the “Create Credentials” and select the OAuth Client ID and copy the both client_id and client_secret and keep these safe becuase its sensitive data.</p><p>And the last remaining settings for specifies the redirection after login/logout and which all-auth’s adapter is use in this project.</p><p><strong>Now see the code of other files:</strong></p><pre># django_oauth/urls.py<br><br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;api/&#39;,include(&#39;accounts.urls&#39;)),<br>    path(&#39;accounts/&#39;,include(&#39;allauth.urls&#39;)),<br>]</pre><p>here i specifying my app’s url will start with ‘api/’ tag, and the all-auth’s urls starts with ‘accounts/’ tag.</p><pre>from django.urls import path<br>from .views import GoogleLoginSuccessView<br>from rest_framework_simplejwt.views import TokenRefreshView<br><br>urlpatterns = [<br>    path(&#39;token/refresh/&#39;,TokenRefreshView.as_view(),name=&quot;refresh-token&quot;),<br>    path(&quot;google/success/&quot;,GoogleLoginSuccessView.as_view(),name=&quot;success-view&quot;),<br>]</pre><p>this is my accounts app’s endpoints.</p><p>now, let’s create the views for our project:</p><pre># accounts/views.py<br><br>from rest_framework.response import Response<br>from rest_framework.views import APIView<br>from rest_framework import status<br>from .serializers import RegisterSerializer, CustomTokenSerializer, LogoutSerializer<br>from rest_framework_simplejwt.views import TokenObtainPairView<br>from rest_framework.permissions import IsAuthenticated<br>from rest_framework_simplejwt.tokens import RefreshToken<br><br>class RegisterView(APIView):<br>  ...    <br>class LoginView(TokenObtainPairView):<br>  ...<br>class ProfileView(APIView):<br>  ...<br><br>class LogoutView(APIView):<br>  ...<br>class GoogleLoginSuccessView(APIView):<br>    def get(self, request):<br><br>        access = request.session.get(&quot;access&quot;)<br>        refresh = request.session.get(&quot;refresh&quot;)<br><br>        if not access:<br>            return Response({&quot;error&quot;: &quot;tokens not found&quot;}, status=400)<br><br>        return Response({<br>            &quot;access&quot;: access,<br>            &quot;refresh&quot;: refresh<br>        })</pre><p><strong>let’s discuss about our views:</strong></p><ul><li>Our first view is <strong>RegisterView</strong> because firstly we want to register the user, in this view we inherit the APIView class from rest_framework.views, we use the post method because we want to post the data.</li><li>Next are LoginView, ProfileView, LogoutView for perform these operations.</li><li>Last one is for completely OAUTH, in this project we use the GOOGLE as a 3rd party provider, so we create the GoogleLoginSuccessView, this view is for when we loggedin by google then what happens next, here we issue the access and refresh tokens both for maintain the authenticity of the user.</li></ul><p>now serializers.py:</p><pre># accounts/serializers.py<br><br>from rest_framework import serializers<br>from .models import User<br>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer <br>from rest_framework_simplejwt.tokens import RefreshToken<br><br>class RegisterSerializer(serializers.ModelSerializer):<br>  ...<br><br>class CustomTokenSerializer(TokenObtainPairSerializer):<br>    ...<br><br>class LogoutSerializer(serializers.Serializer):<br>    ...</pre><p><strong>Serializer</strong> is like a middleman between the client’s data format and server’s data format. It converts the data from other format into the server’s relevant data format for perform operation in database and generates the response according to the request and serves it and <strong>Vice-Versa.</strong></p><p>Here we import the built-in serializers from rest_framework and inherit into our serializers(in <strong>RegisterSerializer</strong>, <strong>CustomTokenSerializer, LogoutSerializer</strong>).</p><pre># accounts/models<br><br>from django.db import models<br>from django.contrib.auth.models import AbstractUser<br><br>class User(AbstractUser):<br>    phone = models.CharField(max_length=15,null=True,blank=True)</pre><p>This is our model for this project. You may see a ‘phone’ field in the model even though it’s not used anywhere. This was added just to show how we can customize Django’s default user model while implementing OAuth.</p><pre>from allauth.account.adapter import DefaultAccountAdapter<br>from allauth.socialaccount.adapter import DefaultSocialAccountAdapter<br>from rest_framework_simplejwt.tokens import RefreshToken<br>from django.shortcuts import redirect<br><br>class AccountAdapter(DefaultAccountAdapter):<br>    def get_login_redirect_url(https://medium.com/self,%20request):<br><br>        user = request.user<br>        refresh = RefreshToken.for_user(user)<br><br>        request.session[&quot;access&quot;] = str(refresh.access_token)<br>        request.session[&quot;refresh&quot;] = str(refresh)<br><br>        return &quot;http://127.0.0.1:8000/api/google/success/&quot;<br><br>class SocialAdapter(DefaultSocialAccountAdapter):<br>    def pre_social_login(self, request, sociallogin):<br><br>        email = sociallogin.account.extra_data.get(&quot;email&quot;)<br><br>        if email:<br>            from django.contrib.auth import get_user_model<br>            User = get_user_model()<br><br>            try:<br>                user = User.objects.get(email=email)<br>                sociallogin.connect(request, user)<br>            except User.DoesNotExist:<br>                pass</pre><p>This is our adapters, before jumping into the code, it’s important to understand what adapters are and why we need them. In django all-auth, adapters are special classes that gives us the facility to customize the authentication process. We override specific adapter methods and add our own logic at certain points during login or registration.</p><p>In simple terms, you can think of adapters as checkpoints in the authentication process. Django runs its normal authentication flow, but when it reaches one of these checkpoints, our custom logic gets executed. We used adapters because the default authentication flow does not generate JWT tokens or automatically link accounts.</p><p>In this implementation, we used two adapters:</p><p><strong>AccountAdapter</strong> — controls login behaviour and redirect logic.</p><p><strong>SocialAccountAdapter</strong> — manages the behaviour of OAuth providers (such as Google, Facebook, etc.).</p><h3>Problems which i faced during the implementation and how i solved them ?</h3><ol><li><strong>Unsaved user error:</strong></li></ol><pre>ValueError: save() prohibited to prevent data loss due to unsaved related object &#39;user&#39;</pre><p>why it occurs:</p><p>when i tried to generate the tokens inside the pre_social_login(). But, in OAuth lifecycle this method runs before user is saved. So, the root cause was that i tried to generating JWT before the user existed in the database.</p><p>2. When i register the user manually without using social signup then after this when i tried to signup through social account the data matches and occurred the <strong>“unique constraint failed”</strong> error because i only matches the primary key not the username and email</p><pre>if user.pk is None:<br>    user.save()</pre><p>so the same data insert again and server throws the error. The real root cause that you can admit or see is that I interfered with the framework’s internal save mechanism.</p><p>3. Now, i searched om google and give time and i got the solution so i shift my logic to login(). But I noticed that because of this, sometimes tokens were being received and sometimes not, and then a new error appeared.</p><p>I searched about this, and then I found out that the real error was because I hadn’t properly understood the OAuth lifecycle. That’s why the error was occurring. After understanding it, I realized that:</p><pre>pre_social_login :before save<br>save_user :new users only<br>login :after authentication<br>AccountAdapter :redirect</pre><blockquote>JWT generation should happen after full authentication, not during social login linking.</blockquote><h3>Solution:</h3><p>Instead of generating JWT tokens inside the SoicalAdapter we move this logic to AccountAdapter.</p><pre>AccountAdapter.get_login_redirect_url()</pre><p>and then we generate:</p><pre>refresh = RefreshToken.for_user(user)<br>request.session[&quot;access&quot;] = str(refresh.access_token)<br>request.session[&quot;refresh&quot;] = str(refresh)<br><br>return &quot;http://127.0.0.1:8000/api/google/success/&quot;</pre><p>and our success endpoint read the tokens from the session.</p><p>The main challenge was understanding django-allauth’s authentication lifecycle. Initially, I generated JWT tokens in an early hook before the user was persisted in the database. After mapping the complete flow, I moved token generation to a post-authentication stage, which resolved all state inconsistencies.</p><p>You can refer my <a href="https://github.com/mangalji/Oauth_implementation_3_self">GitHub</a> for complete code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=881a1508cb7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>