<?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 CodeUmwelt on Medium]]></title>
        <description><![CDATA[Stories by CodeUmwelt on Medium]]></description>
        <link>https://medium.com/@CodeUmwelt?source=rss-1cc6fea2cd33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aUKTO1g90wq66k9-m5Hetw.png</url>
            <title>Stories by CodeUmwelt on Medium</title>
            <link>https://medium.com/@CodeUmwelt?source=rss-1cc6fea2cd33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:32:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@CodeUmwelt/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[Django REST API with Custom User Model & JWT Cookie Authentication]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-e04caff57d61?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/e04caff57d61</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:25:01 GMT</pubDate>
            <atom:updated>2024-09-07T20:25:01.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h4>A series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDr_qI5gB18psJs8qBIUEw.png" /></figure><p>Hello 👋</p><p>I’m very excited to bring you this series of articles, as they are the first articles I publish on Medium, and it took me quite some time to prepare them 😃</p><p>Once you’ve followed all the steps detailed here, you’ll be able to savor the full satisfaction of having implemented a Django REST API, with a full authentication system using JWT Cookies, and ready to be extended with the models of your choice (endpoints for a todo app, for example) 😎</p><p>What does it mean more precisely?</p><p>Well, when you’re done with it, you’ll have the following features:</p><ul><li>A simple custom User model (that you can extend later if need be)</li><li>A series of endpoints provided by the <em>dj-rest-auth</em> library to:<br>- Manage the user registration process, with an email verification feature<br>- Manage login and logout of your users (with authentication based on email &amp; password) and “session management” based on <em>HttpOnly</em> &amp; <em>Secure</em> cookies containing JWT authentication tokens<br>- Manage user password change and password reset<br>- User information retrieval and update</li></ul><p>Starting to feel interested? 😁</p><p>If so, then come and follow me on this journey! But first let’s go through some additional introduction information.</p><p>ℹ️ Some prerequisites information ℹ️</p><ul><li>You will be more comfortable when going through this tutorial if you have some basic knowledge about HTTP, REST APIs, Docker, Django and Django REST framework</li><li>You will need an account on the following platforms (free account is enough):<br>- <a href="https://github.com/">github.com</a><br>- <a href="https://www.docker.com/">docker.com</a> (to access Docker Hub)</li><li>You will need the following software to be installed on your machine:<br>- VS Code (or any other IDE you are comfortable with and that ideally has some support for Python)<br>- Git (configured with proper user name &amp; email, and the needed credentials to access your GitHub account)<br>- Docker</li></ul><p>🗺️ Content Overview 🗺️</p><ul><li>Project Setup</li><li>PostgreSQL DB Setup</li><li>Custom Django User Model Implementation</li><li>Structure the Django Project for API Versioning</li><li>Configure Authentication Using JWT HttpOnly &amp; Secure Cookies</li></ul><p>📣 Finally, a few words of encouragement 📣</p><p>👉 Try to enjoy yourself. If you run into difficulties, don’t beat yourself up — it’s normal (all developers run into problems all the time, it’s part of the job)</p><p>👉 Stay motivated and enthusiastic, and I assure you that when you reach the end of the project, you’ll feel genuine satisfaction!</p><p>Whenever you are ready, you can go to the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-project-setup-b247f53ffb96">next article</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e04caff57d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST API with Custom User Model & JWT Cookie Authentication — Project Setup]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-project-setup-b247f53ffb96?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/b247f53ffb96</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <category><![CDATA[software-devlopment]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:23:40 GMT</pubDate>
            <atom:updated>2024-09-09T08:31:59.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h3>Django REST API with Custom User Model &amp; JWT Cookie Authentication — Project Setup</h3><h4>This is the 2nd in a series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><h4>⏮️ <a href="https://medium.com/@CodeUmwelt/e04caff57d61">Previous article</a></h4><h4>⏭️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-postgresql-db-setup-797ff1e48fb5">Next article</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qE_seOy8YY8FeNTkqXaVQ.jpeg" /></figure><p>In this article, we will take care of setting up our project. We will go through the following steps:</p><p><strong>PART 1</strong> — Git &amp; GitHub setup<br><strong>PART 2</strong> — Specify our first dependency<br><strong>PART 3</strong> — Set up our Docker environment<br><strong>PART 4</strong> — Start our Django project<br><strong>PART 5</strong> — Test running our project for the first time</p><p>Let’s get down to business! 🏁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBoQrSXpB8DZMvP_ScdckA.jpeg" /></figure><p>Log into <a href="https://github.com/">github.com</a> and create a new repo.</p><p>Choose a name and fill a short description.</p><p>Choose your repo type, public or private.</p><p>Add a README file and a Python <em>.gitignore</em> template file.</p><p>Finally, leave the license to “None” unless you have specific needs, and hit the “Create repository” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*99FlEbof1oKU6ukE2-0gXw.png" /></figure><p>You will end up with a screen like the following one. Click on the green “Code” dropdown button, select the cloning method of your choice (HTTPs or SSH for example) and copy the clone reference. Save it for the next step below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6c9-H1sTwTf0993vYdeYkA.png" /></figure><p>Create a directory at the destination of your choice on your computer.</p><p>Cd into this new directory and git clone the project from GitHub (use the clone reference you save previously).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NX0k9Nw9RYob2OnG06SO0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K7zzPSWsFm6vPfs_mUhpdg.jpeg" /></figure><p>Open the project directory with your IDE.</p><p>Create a requirements.txt file at the root of the project. This is where you will define your dependencies. Adding lowest and highest version for each dependency is a good practice, to make you stay up to date with recent changes for your dependencies, without taking major changes however.</p><p>Our first dependency is Django, so add it to our requirements.txt file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nSQVSiiM1837sG_bzb_06w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e8vrmscYBiGv6Tt0zPk3QQ.jpeg" /></figure><p>Create a Dockerfile at the root of your project. This is the file used by Docker to build our image. Fill it with the below content.</p><p>You can update the Python Alpine version at the top if there’s a more recent version at the time you follow this tutorial.</p><pre>FROM python:3.12-alpine3.20<br>LABEL maintainer=&quot;CodeUmwelt&quot;<br><br>ENV PYTHONUNBUFFERED 1<br><br>COPY ./requirements.txt /tmp/requirements.txt<br>COPY ./app /app<br>WORKDIR /app<br>EXPOSE 8000<br><br>RUN python -m venv /py &amp;&amp; \<br>    /py/bin/pip install --upgrade pip &amp;&amp; \<br>    /py/bin/pip install -r /tmp/requirements.txt &amp;&amp; \<br>    rm -rf /tmp &amp;&amp; \<br>    adduser \<br>    --disabled-password \<br>    --no-create-home \<br>    django-user<br><br>ENV PATH=&quot;/py/bin:$PATH&quot;<br><br>USER django-user</pre><p>Create a <em>.dockerignore</em> file at the root of your project to specify files to be ignored from the Docker context when building image.</p><pre># Git<br>.git<br>.gitignore<br><br># Docker<br>.docker<br><br># Python<br>app/__pycache__/<br>app/*/__pycache__/<br>app/*/*/__pycache__/<br>app/*/*/*/__pycache__/<br>.env/<br>.venv/<br>venv/</pre><p>Create an “app” directory at the root of the project.</p><p>From your terminal, at the root of the project, test building the docker image with “docker build .“ (do not forget the ‘.’ character in the command).</p><p>Create a docker-compose.yml file at the root of the project. Docker compose is a convenient tool that allows us to define a multi-container setup in a single YAML file. This is very useful because later, we will also need a container for our database.</p><pre>services:<br>  app:<br>    build:<br>      context: .<br>    ports:<br>      - &quot;8000:8000&quot;<br>    volumes:<br>      - ./app:/app<br>    command: &gt;<br>      sh -c &quot;python manage.py runserver 0.0.0.0:8000&quot;</pre><p>Try building image using docker-compose (“docker-compose build”). It effectively does the same thing as “docker build” but using the docker-compose.yml file.</p><p>In your IDE, you should have the same hierarchy as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*Kn1IpXzB6zhgUDxSZ2XcsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vqRF1dV2w0h6pgLtNH9jlw.jpeg" /></figure><p>Now we will start our Django project.</p><p>Since we use Docker in our development environment, we will not directly type the Django commands. We will instead have to start a container and pass it the command so that it executes inside it.</p><p>From your terminal, at the root of the project, type the following command.</p><ul><li>It will use docker-compose to start a container, using the <em>app</em> directory as the Docker context,</li><li>“-rm” will remove the container after running the command,</li><li>“sh -c” waits for a command to be passed to the shell inside the container.</li></ul><pre>docker-compose run --rm app sh -c &quot;django-admin startproject app .&quot;</pre><p>If you look again into your IDE, you will see that new content has been created inside the “app” folder you previously created:</p><ul><li>The Django <em>manage.py</em> file</li><li>An “app” directory, which is the Django project main folder</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*ncEa2BKeYWmHyKFfjgWpJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKUyhmnJFsXRFl92_pr16A.jpeg" /></figure><p>Test running the project with “docker-compose up”. You should see output similar to the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NyDqPva8DLCWlwwcFGUBLQ.png" /></figure><p>Then open a browser and go to <em>http://localhost:8000</em>. You should see your Django app now running!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLW1h_3vl81fmeNvbYeqwQ.png" /></figure><p>Once you’ve checked it is working, you can shut it down with Ctrl+c and then typing “docker-compose down”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkdxCf-UKTY_xsWRvo0MA.jpeg" /></figure><p>Lastly, do a quick git commit to save your code state and push it to your GitHub repository.</p><pre>git add .<br>git commit -m &quot;project setup&quot;<br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S01Tl8Ez2M-GQPWe-VrnLw.jpeg" /></figure><p>That’s all for this project setup article.</p><p>In the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-postgresql-db-setup-797ff1e48fb5">next article</a> of this series, we will focus on setting up a PostgreSQL database for the persistence of our application’s data.</p><p>If you liked the content of this article, do not hesitate to clap/highlight, share the article, or follow me if you want to read other similar articles.</p><p>See ya! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b247f53ffb96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST API with Custom User Model & JWT Cookie Authentication — PostgreSQL DB Setup]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-postgresql-db-setup-797ff1e48fb5?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/797ff1e48fb5</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:20:50 GMT</pubDate>
            <atom:updated>2024-12-13T16:41:41.314Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h3>Django REST API with Custom User Model &amp; JWT Cookie Authentication — PostgreSQL DB Setup</h3><h4>This is the 3rd in a series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><h4>⏮️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-project-setup-b247f53ffb96">Previous article</a></h4><h4>⏭️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-custom-django-user-model-7b5a697665de">Next article</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ttwm_tLr5RuxKGO6CY6u7g.jpeg" /></figure><p>In this article, we will take care of setting up a PostgreSQL DB for the persistance of our project’s data. We will cover the following topics:</p><p><strong>PART 1</strong> — Add a PostgreSQL database service to our docker compose configuration<br><strong>PART 2</strong> — Install Psycopg as a PostgreSQL database adapter for our Django project<br><strong>PART 3</strong> — Configure the PostgreSQL database in Django <em>settings.py</em><br><strong>PART 4</strong> — Create a Django management command to cope with database race condition</p><p>Here we go! 🏁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFd1iD0HQNaWDHlHqoorHg.jpeg" /></figure><p>Since we are using Docker in our development environment, we will setup our database as a Docker service.</p><p>In order to do that, we will add several thing to our docker compose configuration:</p><ul><li>Add a new “volumes” section to setup a managed volume that we’ll name “db-localdev-data”</li><li>Under the “services” section, add a new “db” service, with three subsections:<br>- <strong>image</strong>: we use the postgres:13-alpine image<br>- <strong>volumes</strong>: we bind the <em>/var/lib/postgresql/data</em> path of our postgres Alpine container file system to our <em>db-localdev-data</em> managed volume<br>- <strong>environment</strong>: we specify values for the name of a database to create when the Postgres DB service is started, and a DB user and password to connect to the DB</li><li>Under the “services &gt; app” section, we setup the “app” service to depend on the “db” service, and we pass to the app service some environment variables to be able to connect to the DB (DB host, name, user &amp; password)</li></ul><p>Below is the new version of our <em>docker-compose.yml</em> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0uYaINj0-bfve2vqcXYZZw.png" /></figure><p>With the “docker-compose up” command, we can test that the services start properly. After typing the command, you should see logs for both the app and db services. Database logs should indicate that the database is ready to accept connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D3R6ovTxWQjAvzyY69hgkA.jpeg" /></figure><p>In order for our Django application to communicate with our DB, we must install a PostgreSQL database adapter. We’ll use “Psycopg” for that purpose.</p><p>There are two options for Psycopg:</p><ul><li>A precompiled “binary” option that works consistently on many systems and installs a self-contained package with all the needed libraries</li><li>The classic option that is compiled for your specific system when installed on it</li></ul><p>The second option is quicker since it is compiled specifically for your system. But it has some dependencies, including build dependencies that must be present on your system for the installation to work successfully.</p><p>So we would have first to find the name of all these dependencies (specifically for the Alpine OS our app image uses), and then modify the Dockerfile so that dependencies are installed when building the image.</p><p>The build dependencies can be temporarily installed just for the build step, and removed at the end of the build process (since they’re not needed after the build and it helps keeping our image as lightweight as possible). After modifying the Dockerfile, we would have to modify our requirements.txt file to add the psycopg package to the list of our dependencies.</p><p>Then, we would docker-compose build and finally start our services.</p><p>However, using the first option is simpler.</p><p>Morever, the Psycopg installation documentation gives the following warning:</p><blockquote>“You must be able to troubleshoot an extension build, for instance you must be able to read your compiler’s error message. If you are not, please don’t try this and follow the binary installation instead.”</blockquote><p>In short, until you really need the extra bit of performance obtained with the “local” install (i.e. not “binary” install), I advise you to go with the binary installation.</p><p>So we’ll go with the first option. Hence, we do not need to change the Dockerfile to add the build dependencies. We just need to update our requirements.txt file to add “psycopg[binary]”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*_d0ShqxT2whlSxFWLhScOQ.png" /></figure><p>Finally, type “docker-compose build” to make sure you can properly build the image with the new psycopg dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZ6qpfOSMNUf5XKVs0fU_Q.jpeg" /></figure><p>By default, Django uses a SQLite database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46zRs8V7Xw1Uqdjob9QA0A.png" /></figure><p>Since we want to use a PostgreSQL database, we have to update our “DATABASES” setting in our project’s <em>settings.py</em> file:</p><ul><li>We specify the PostgreSQL value for the “ENGINE” setting</li><li>We setup DB host, DB name, DB user and password. For that, we inject values from environment variables (remember, we setup these values in our docker compose configuration)</li><li>Since we use the “os” module to access environment variables, we need to import this module at the top of <em>settings.py</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rD79W6TW_L-5g7oyyaIZUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIHiXFSEBa9z9ZAYur7Mfg.png" /></figure><p>Note that the db.sqlite3 file that was created by default by Django can be deleted, since we won’t use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tLhBUuL6pQxwZr6jnsY_uA.jpeg" /></figure><p>The “depends_on” statement in our docker-compose.yml file ensures that our db service is started before starting our app service, but it does not ensure that the actual PostgreSQL database application inside the db service is running.</p><p>To fix this race condition, we will implement a custom Django management command, that we will name “db_readiness”. By adding this command as the first step of the command used to start the “app” service (in our docker compose configuration), we will ensure that the database application is running before starting the actual “app” service.</p><p>We will first create a “core” app in the Django project, and we will put our Django management command in it.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py startapp core&quot;</pre><p>We must not forget to add the “core” app to INSTALLED_APPS in Django <em>settings.py</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPGYxc5bswxGt45qwOirbA.png" /></figure><p>To create the db_readiness management command:</p><ul><li>Create a “management” folder under the “core” folder, and an <em>__init__.py</em> file inside it (this file is needed to tell python this folder is a python package)</li><li>Create a “commands” folder under the “management” folder, and an <em>__init__.py</em> file inside it, as well as a <em>db_readiness.py</em> file</li><li>Implement the actual management command in the <em>db_readiness.py</em> file, with the content below</li></ul><pre>&quot;&quot;&quot;<br>Django command to ensure the PostgreSQL database is ready.<br>&quot;&quot;&quot;<br><br>import time<br><br>from django.core.management.base import BaseCommand<br>from django.db.utils import OperationalError<br><br>from psycopg import OperationalError as PsycopgOpError<br><br><br>class Command(BaseCommand):<br>    &quot;&quot;&quot;Django command waiting for database readiness.&quot;&quot;&quot;<br><br>    def handle(self, *args, **options):<br>        &quot;&quot;&quot;Entry point for command.&quot;&quot;&quot;<br>        self.stdout.write(&quot;Waiting for database readiness...&quot;)<br>        is_db_up = False<br>        while is_db_up is False:<br>            try:<br>                self.check(databases=[&quot;default&quot;])<br>                is_db_up = True<br>            except (PsycopgOpError, OperationalError):<br>                self.stdout.write(&quot;Database not ready yet...&quot;)<br>                time.sleep(1)<br><br>        self.stdout.write(self.style.SUCCESS(&quot;Database now ready&quot;))</pre><p>Finally, we’ll use our db_readiness command in the <em>docker-compose.yml</em> file, in the “app” service command, before running the HTTP server. We will also add the Django <em>migrate</em> command to make sure all pending models’ migrations are performed before starting the app service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLQrSz617aXJALRIWQVL7g.png" /></figure><p>You can test everything is working as expected by running “docker-compose up”, you should not have any error logs.</p><p>You can also access one more time <em>http://localhost:8000</em>, and you should still see the default Django project page with the moving rocket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkdxCf-UKTY_xsWRvo0MA.jpeg" /></figure><p>Lastly, do a quick git commit to save your code state and push it to your GitHub repository.</p><pre>git add .<br>git commit -m &quot;postgresql DB setup&quot;<br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S01Tl8Ez2M-GQPWe-VrnLw.jpeg" /></figure><p>That’s all for this PostgreSQL DB setup article. Congratulations for making it this far!</p><p>In the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-custom-django-user-model-7b5a697665de">next article</a> of this series, we will focus on implementing a custom Django user model.</p><p>If you liked the content of this article, do not hesitate to clap/highlight, share the article, or follow me if you want to read other similar articles.</p><p>See ya! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=797ff1e48fb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST API with Custom User Model & JWT Cookie Authentication — Custom Django User Model…]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-custom-django-user-model-7b5a697665de?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5a697665de</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:17:45 GMT</pubDate>
            <atom:updated>2024-11-17T16:21:09.326Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h3>Django REST API with Custom User Model &amp; JWT Cookie Authentication — Custom Django User Model Implementation</h3><h4>This is the 4th in a series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><h4>⏮️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-postgresql-db-setup-797ff1e48fb5">Previous article</a></h4><h4>⏭️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-structure-the-django-project-163467271d61">Next article</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aNPhoda-aFU2z-DP3bt8w.jpeg" /></figure><p>In this article, we will implement a custom Django user model. It will be quite frugal, since the main goal is just to demonstrate authentication features in later articles.</p><p>Moreover, it is a good idea to implement a custom user model for any new Django project. This is because when you decide to use the default Django user model, certain changes to this model can be difficult to apply down the road. It’s much simpler to create a custom user model right from the beginning.</p><p>We will cover the following topics:</p><p><strong>PART 1</strong> — Add unit tests for our custom user model<br><strong>PART 2</strong> — Implement our custom user model<br><strong>PART 3</strong> — Make migrations and migrate database<br><strong>PART 4</strong> — Add Django admin site support for our user model<br><strong>PART 5</strong> — Implement a custom user serializer class</p><p>Let’s get started! 🏁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFy55SCw51ob8QmDrPzI0g.jpeg" /></figure><p>It is a good practice to use unit tests in any application. Django provides capabilities for implementing such tests, and we will showcase that just for performing some tests on our user model.</p><p>So we will start by implementing tests for our custom user model. Adding tests for some features before implementing the said features is a coding practice called “Test-driven development” (TDD).</p><p>In our project, under the “app &gt; core” folder, create a new folder called “tests”. And in this new folder, create two files:</p><ul><li>An <em>__init__.py</em> file</li><li>A <em>test_models.py</em> file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*KOlq5evIjl82abJZR-NpOw.png" /></figure><p>The <em>test_models.py</em> file will contain methods for unit testing our application’s models. Fill it with the following code.</p><pre>&quot;&quot;&quot;<br>Tests for the models of the application.<br>&quot;&quot;&quot;<br><br>from django.test import TestCase<br>from django.contrib.auth import get_user_model<br><br><br>class ModelTests(TestCase):<br><br>    def test_create_user_with_email_ok(self):<br>        &quot;&quot;&quot;Test creating a user with an email address works.&quot;&quot;&quot;<br>        email = &quot;testuser1@example.com&quot;<br>        password = &quot;testPwd1!&quot;<br>        user = get_user_model().objects.create_user(<br>            email=email,<br>            password=password,<br>        )<br><br>        self.assertEqual(user.email, email)<br>        self.assertTrue(user.check_password(password))<br><br>    def test_created_user_email_normalized(self):<br>        &quot;&quot;&quot;Test email address of new users is normalized.&quot;&quot;&quot;<br>        test_emails = [<br>            [&quot;testuser1@EXAMPLE.com&quot;, &quot;testuser1@example.com&quot;],<br>            [&quot;TestUser2@Example.com&quot;, &quot;TestUser2@example.com&quot;],<br>            [&quot;TESTUSER3@EXAMPLE.com&quot;, &quot;TESTUSER3@example.com&quot;],<br>            [&quot;testuser4@example.COM&quot;, &quot;testuser4@example.com&quot;],<br>        ]<br>        for email, expected in test_emails:<br>            user = get_user_model().objects.create_user(email, &quot;testPwd1!&quot;)<br>            self.assertEqual(user.email, expected)<br><br>    def test_create_user_without_email_ko(self):<br>        &quot;&quot;&quot;Test creating a user without an email address fails.&quot;&quot;&quot;<br>        with self.assertRaises(ValueError):<br>            get_user_model().objects.create_user(&quot;&quot;, &quot;testPwd1!&quot;)<br><br>    def test_create_superuser(self):<br>        &quot;&quot;&quot;Test creating a superuser.&quot;&quot;&quot;<br>        user = get_user_model().objects.create_superuser(<br>            &quot;testadmin@example.com&quot;,<br>            &quot;testPwd1!&quot;,<br>        )<br><br>        self.assertTrue(user.is_superuser)<br>        self.assertTrue(user.is_staff)</pre><p>The three first tests respectively test that:</p><ul><li>We can create a user when we provide an email</li><li>The provided email is normalized (everything after the @ is lowercased)</li><li>We cannot create a user without providing an email</li></ul><p>The last test checks that superuser creation works fine.</p><p>Since we decided to put our tests for the core app into a <em>tests</em> subfolder, we have to delete the <em>tests.py</em> file that is directly under the <em>core</em> folder. This is because, for a given app, Django requires to use either test files directly under the app folder, or under a dedicated <em>tests</em> folder, but not both at the same time.</p><p>You can now run the tests with the below command.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py test&quot;</pre><p>They should fail since we haven’t implemented the corresponding features yet. This is part of the TDD dance 😉</p><p>In the next part, we will implement the features to make our tests pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcjVaoMLk3d4XLjnP29a5A.jpeg" /></figure><p>Open the <em>models.py</em> file under the core application folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*0LU-tqyAE0O6Pfb1qTfqHw.png" /></figure><p>Below is the code for our implementation of the user model.</p><pre>&quot;&quot;&quot;<br>The models of the application.<br>&quot;&quot;&quot;<br><br>from django.conf import settings<br>from django.db import models<br>from django.contrib.auth.models import (<br>    AbstractBaseUser,<br>    BaseUserManager,<br>    PermissionsMixin,<br>)<br><br><br>class UserManager(BaseUserManager):<br>    &quot;&quot;&quot;Custom BaseUserManager for the app users.&quot;&quot;&quot;<br><br>    def create_user(self, email, password=None, **extra_fields):<br>        if not email:<br>            raise ValueError(&quot;Email address is mandatory for users.&quot;)<br>        user = self.model(email=self.normalize_email(email), **extra_fields)<br>        user.set_password(password)<br>        user.save(using=self._db)<br><br>        return user<br><br>    def create_superuser(self, email, password):<br>        user = self.create_user(email, password)<br>        user.is_staff = True<br>        user.is_superuser = True<br>        user.save(using=self._db)<br><br>        return user<br><br><br>class User(AbstractBaseUser, PermissionsMixin):<br>    &quot;&quot;&quot;The app custom user model.&quot;&quot;&quot;<br><br>    # The email field must be unique since we use it as the unique<br>    # identifier (see below USERNAME_FIELD)<br>    email = models.EmailField(max_length=255, unique=True)<br>    name = models.CharField(max_length=255)<br>    is_active = models.BooleanField(default=True)<br>    is_staff = models.BooleanField(default=False)<br><br>    objects = UserManager()<br><br>    # We use the email field as the unique identifier<br>    USERNAME_FIELD = &quot;email&quot;</pre><p>Our user model has an <em>email</em> and a <em>name</em>.</p><p>The <em>email</em> field is set as its unique identifier.</p><p>Two other fields are <em>is_active</em> (to know if the user is active or not), and <em>is_staff</em> (is true if user has access to the Django admin site, false otherwise).</p><p>We also implemented a custom manager for our user model. If you wanna see details about that, check <a href="https://docs.djangoproject.com/en/5.1/topics/auth/customizing/#writing-a-manager-for-a-custom-user-model">this page of the Django documentation</a>.</p><p>Finally, we must add a small but important change in our <em>settings.py</em>. We have to tell Django that the user model to plug into Django’s authentication system is the one we just created. So we add the following line at the bottom of our <em>settings.py</em>.</p><pre>AUTH_USER_MODEL = &quot;core.User&quot;</pre><p>The next part is about preparing the database migrations corresponding to our new models modifications, and applying these migrations to our database. This is needed before our tests can pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgOx9SwwxKbC5emsSXFxJw.jpeg" /></figure><p>Run the following command to make migrations. Note that we use our previously created “db_readiness” management command. This is because the <em>makemigrations</em> command has to check which migrations may already have been applied to the database. So we need to make sure the database is up before running <em>makemigrations</em>.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py db_readiness &amp;&amp; python manage.py makemigrations&quot;</pre><p>You should get an output similar to the following one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex4p-lNuE8phd3nkmGIJlQ.png" /></figure><p>Then, we can “migrate” the database.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py db_readiness &amp;&amp; python manage.py migrate&quot;</pre><p>If you get an error message related to inconsistent migration history, then:</p><ul><li>Delete the <em>0001_initial.py</em> file that was created via <em>makemigrations</em></li><li>Shut down your project containers with “docker-compose down”</li><li>Find the name of the Docker volume containing the database data with “docker volume ls”</li><li>Clear the database data with “docker volume rm NAME_OF_DB_DATA_VOLUME”</li><li>Rerun the two commands (for <em>makemigrations</em> and for <em>migrate</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5HUVSiGlE4cm-Wumj5W5g.png" /></figure><p>If you rerun the unit tests now, they should all pass (remember: <em>docker-compose run — rm app sh -c “python manage.py test”</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GDKro3plVrymmnV4RaR-lQ.png" /></figure><p>Additionally, the creation of a super user should still work and you should be able to connect to the Django admin site. Since we are going to use it in the next part, let’s create such a user.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py createsuperuser&quot;</pre><p>An email and a password (as well as password confirmation) will be asked. Then, the user should be created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhs_gywaI2UHuaJnpR8nrw.png" /></figure><p>You should be able to access the Django admin site, by going to http://<em>localhost:8000/admin</em> and providing the credentials in the login form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzG_-n6uR4j0_Mgfy2jR8w.png" /></figure><p>Once you’ve logged in, you should see something similar to the below screenshot. You’ll probably notice that there’s no trace of users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHCsNG6HrGNjj4kSh9GEuA.png" /></figure><p>This is because we did not configure our custom user model to be visible in the Django admin site. In the next part, we will do the required changes to fix that and see our users in the admin site, with a custom display of the user fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PdBO24x4LBsB6xngBnfxKw.jpeg" /></figure><p>In order to display our users in the Django admin site, we have to register the <em>core.user</em> model with this site. This is done in the “app &gt; core &gt; admin.py file”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*LuyIA3BlqJryh_lql-sLhQ.png" /></figure><p>Below is the code we will add to this file.</p><pre>from django.contrib import admin<br>from django.contrib.auth.admin import UserAdmin as BaseUserAdmin<br><br>from core import models<br><br><br>class UserAdmin(BaseUserAdmin):<br>    &quot;&quot;&quot;Define the admin pages for users.&quot;&quot;&quot;<br><br>    ordering = [&quot;id&quot;]<br>    list_display = [&quot;email&quot;, &quot;name&quot;]<br>    fieldsets = (<br>        (&quot;Main Information&quot;, {&quot;fields&quot;: (&quot;email&quot;, &quot;password&quot;)}),<br>        (&quot;Personal Information&quot;, {&quot;fields&quot;: (&quot;name&quot;,)}),<br>        (<br>            &quot;Permissions&quot;,<br>            {<br>                &quot;fields&quot;: (<br>                    &quot;is_active&quot;,<br>                    &quot;is_staff&quot;,<br>                    &quot;is_superuser&quot;,<br>                )<br>            },<br>        ),<br>        (&quot;Additional Information&quot;, {&quot;fields&quot;: (&quot;last_login&quot;,)}),<br>    )<br>    readonly_fields = [&quot;last_login&quot;]<br>    add_fieldsets = (<br>        (<br>            None,<br>            {<br>                &quot;fields&quot;: (<br>                    &quot;email&quot;,<br>                    &quot;password1&quot;,<br>                    &quot;password2&quot;,<br>                    &quot;name&quot;,<br>                    &quot;is_active&quot;,<br>                    &quot;is_staff&quot;,<br>                    &quot;is_superuser&quot;,<br>                ),<br>            },<br>        ),<br>    )<br><br><br>admin.site.register(models.User, UserAdmin)</pre><p>Here are some explanations about this piece of code:</p><ul><li>At the very bottom of the file, we call the <em>admin.site.register</em> function<br>- The first argument registers our custom user model with the admin site<br>- The second argument is a custom <em>UserAdmin</em> class, that extends <em>django.contrib.auth.admin.UserAdmin</em>. It allows us to customize the way our user objects are displayed in various pages of the admin site</li><li>The main part of the code (everything between the imports and the <em>admin.site.register</em> call) is the definition of the custom <em>UserAdmin</em> class. It customizes the display of user information in various admin site pages<br>- The <em>ordering</em> field specifies that in the Admin list page for users, the listed users will be ordered by id<br>- The <em>list_display</em> field tells which user fields are displayed for each user in the users list page<br>- The <em>fieldsets</em> field allows us to specify which user fields should be displayed in the user detail page, and gives us the ability to group these fields in sections of our choice (here we created three sections — “Main Information”, “Personal Information” and “Additional Information”)<br>The <em>readonly_fields</em> prevents us from editing the <em>last_login</em> field in the user details page<br>- The <em>add_fieldsets</em> field is used to tell Django which fields to display in the page for user creation. Here we decided to group all the fields in one section, with no section header</li></ul><p>After saving this configuration and starting your services, you should now see a new <em>Users</em> link on the Django admin home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZzQ7Wr2yhC-vo1SdjY9GA.png" /></figure><p>And if you click on the <em>Users</em> button, you should see something similar to the below screenshot, with a list of user records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J2KAXVoi8eSeCxi71610rw.png" /></figure><p>Finally, if you click on the <em>admin@example.com</em> record (or any name you gave to your created super user), you should see a new page like the one below, with all the sections and fields as configured in our custom <em>UserAdmin</em> class that we registered with the admin site. This page allows you to update or delete the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJPXYdsJdT2RFyryKYNhAw.png" /></figure><p>Django admin also gives you the ability to create a new user. For example, from the Django admin home page, you can click on the « <strong><em>Add+</em></strong> » button located on the « Users » line, and it will bring you to the user creation page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8vQotdIsyr9d93BA-3kjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPSQkn52k7xLHNlA0l7jOA.png" /></figure><p>Before we wrap up this article, let’s do another change that will be useful later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0T6Nw5J8WigVsEXPFxwVrg.jpeg" /></figure><p>We will implement a custom user serializer.</p><p>That will allow us:</p><ul><li>To have a place to customize and have control over how client user data sent to our API is processed to create or update a user. In particular, when updating a user, we can process the password by using the right Django API to encrypt it in our database</li><li>To specify what specific fields should be exchanged between the client and the API for user operations. This will be useful later on when we activate authentication-related REST API endpoints (see <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-configure-authentication-2b33076c4b8e">article 6</a>)</li></ul><p>First, create a new Django app named “user”. This will allow us to organize our project properly, and to add other user-related endpoints for custom features in the future if need be.</p><pre>docker-compose run --rm app sh -c &quot;python manage.py startapp user&quot;</pre><p>Then create a new <em>serializers.py</em> file under “app &gt; user”, and fill it with the following code.</p><pre>&quot;&quot;&quot;<br>Serializers for user-related functionality.<br>&quot;&quot;&quot;<br><br>from django.contrib.auth import (<br>    get_user_model,<br>)<br><br>from rest_framework import serializers<br><br><br>class UserSerializer(serializers.ModelSerializer):<br>    &quot;&quot;&quot;Serializer for user object.&quot;&quot;&quot;<br><br>    class Meta:<br>        model = get_user_model()<br>        fields = [&quot;email&quot;, &quot;password&quot;, &quot;name&quot;]<br>        extra_kwargs = {&quot;password&quot;: {&quot;write_only&quot;: True, &quot;min_length&quot;: 5}}<br><br>    def create(self, validated_data):<br>        &quot;&quot;&quot;Create a user with encrypted password and return the user.&quot;&quot;&quot;<br>        return get_user_model().objects.create_user(**validated_data)<br><br>    def update(self, instance, validated_data):<br>        &quot;&quot;&quot;Update a user and return it.&quot;&quot;&quot;<br>        password = validated_data.pop(&quot;password&quot;, None)<br>        user = super().update(instance, validated_data)<br><br>        if password:<br>            user.set_password(password)<br>            user.save()<br><br>        return user</pre><p>Finally, you can add the “user” app to INSTALLED_APPS in <em>settings.py</em>.</p><p>That’s not mandatory for our project now, but it does not expose any sensitive stuff and it will prevent any oversight in the future.</p><p>That’s it, we’ll now commit our work and wrap up this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkdxCf-UKTY_xsWRvo0MA.jpeg" /></figure><p>Lastly, do a quick git commit to save your code state and push it to your GitHub repository.</p><pre>git add .<br>git commit -m &quot;custom user model&quot;<br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S01Tl8Ez2M-GQPWe-VrnLw.jpeg" /></figure><p>We’re done with our custom user model implementation and its registration in the Django admin site. Once again, congrats for making it this far! 🙌</p><p>In the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-structure-the-django-project-163467271d61">next article</a> of this series, we will organize our project so that we can easily manage API versioning, in case we want to do significant modifications to our API in the future.</p><p>If you liked the content of this article, do not hesitate to clap/highlight, share the article, or follow me if you want to read other similar articles.</p><p>See ya! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5a697665de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST API with Custom User Model & JWT Cookie Authentication — Structure the Django Project…]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-structure-the-django-project-163467271d61?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/163467271d61</guid>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:14:49 GMT</pubDate>
            <atom:updated>2024-09-09T12:01:20.085Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h3>Django REST API with Custom User Model &amp; JWT Cookie Authentication — Structure the Django Project for API Versioning</h3><h4>This is the 5th in a series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><h4>⏮️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-custom-django-user-model-7b5a697665de">Previous article</a></h4><h4>⏭️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-configure-authentication-2b33076c4b8e">Next article</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cggx_mDFX2dAHHJhAYXTew.jpeg" /></figure><p>In this short article, we will quickly update the structure of our Django project in a way that will simplify the versioning of its REST API.</p><p>Baking versioning into your API is a good practice, because it will ease potentially significant changes in the future.</p><p>With versioning, you can limit the duration and magnitude of the impact on user experience, during the period needed to implement the changes.</p><p>Let’s go! 🏁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bEZfn8szoGCSj1d40FcSTA.jpeg" /></figure><p>To implement API versioning, we will simply do the following:</p><ol><li>Create two new apps respectively called “api” and “api_v1”:<br>- <em>docker-compose run --rm app sh -c “python manage.py startapp api”<br></em>- <em>docker-compose run --rm app sh -c “python manage.py startapp api_v1”</em></li><li>Add these apps to INSTALLED_APPS in <em>settings.py</em></li><li>Plug the <em>api</em> app urls into the <em>urlpatterns</em> of the root <em>urls.py</em> (“app &gt; app &gt; urls.py”) (see first picture below)</li><li>Create a <em>urls.py</em> file under “app &gt; api”, and add <em>api_v1</em> urls to api <em>urlpatterns</em> (see second picture below)</li><li>Create a <em>urls.py</em> file under “app &gt; api_v1” (see third picture below). For the moment its <em>urlpatterns</em> are empty</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*wBWzflrodVUz2AUG_1z90w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*UA5ShdGwlVAxfKPFPijVwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*y47ZuIyY7y2WsJOzvMVsTw.png" /></figure><p>Now we can start to add our own API endpoints under <em>api_v1</em>.</p><p>If at some point, we want to rewrite the API structure/features in a second version, we can create a new <em>api_v2</em> app and plug it into api app’s urls as we did for <em>api_v1</em>.</p><p>This way, we can offer the two versions of the API to our consumers in parallel. When API version 1 is fully deprecated, we can shut it down and let everyone continue using API version 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkdxCf-UKTY_xsWRvo0MA.jpeg" /></figure><p>Lastly, do a quick git commit to save your code state and push it to your GitHub repository.</p><pre>git add .<br>git commit -m &quot;api versioning&quot;<br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S01Tl8Ez2M-GQPWe-VrnLw.jpeg" /></figure><p>That’s all for this project setup article. Congratulations for making it this far!</p><p>We now have all the prerequisites ready for moving on to the implementation of specific authentication features, which is the main goal of this series of articles 🤩</p><p>In the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-configure-authentication-2b33076c4b8e">next article</a> of this series, we will focus on configuring Email+Password Authentication Using JWT HttpOnly &amp; Secure Cookies.</p><p>If you liked the content of this article, do not hesitate to clap/highlight, share the article, or follow me if you want to read other similar articles.</p><p>See ya! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=163467271d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django REST API with Custom User Model & JWT Cookie Authentication — Configure Authentication…]]></title>
            <link>https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-configure-authentication-2b33076c4b8e?source=rss-1cc6fea2cd33------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b33076c4b8e</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[dj-rest-auth]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[CodeUmwelt]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 20:13:23 GMT</pubDate>
            <atom:updated>2024-11-18T19:04:13.402Z</atom:updated>
            <content:encoded><![CDATA[<h4>Software Development — Tutos</h4><h3>Django REST API with Custom User Model &amp; JWT Cookie Authentication — Configure Authentication Using JWT HttpOnly &amp; Secure Cookies</h3><h4>This is the 6th in a series of articles about implementing a REST API in Django, using authentication based on JWT cookies.</h4><h4>⏮️ <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-structure-the-django-project-163467271d61">Previous article</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DY50EEtFWSxLqfqAq2Y7Fw.jpeg" /></figure><p>In this article, we will configure our application to switch it from the default Django session authentication to authentication based on JWT cookies.</p><p>We will cover the following topics:</p><p><strong>PART 1</strong> — Install dj-rest-auth<br><strong>PART 2</strong> — Add API documentation for better endpoints visualization<br><strong>PART 3 </strong>— Fine-tuning of the authentication API behavior<br><strong>PART 4</strong> — Configure JWT Cookie authentication</p><p>Let’s get started! 🏁</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dW5NHWThLTXZEb_I0KkF-Q.jpeg" /></figure><p>In order to implement the authentication features we want to implement, we will leverage <em>dj-rest-auth</em>.</p><p>As described in its <a href="https://dj-rest-auth.readthedocs.io/en/latest/">documentation</a>, dj-rest-auth is</p><blockquote>“A set of REST API endpoints to handle User Registration and Authentication tasks. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for User Management. Of course, we’ll add more API endpoints as we see the demand.”</blockquote><p>dj-rest-auth depends on the Django REST framework package, which is “<em>a powerful and flexible toolkit for building Web APIs</em>” (see <a href="https://www.django-rest-framework.org/">here</a>).</p><p>Additionally, dj-rest-auth has the following app structure:</p><ul><li><strong><em>dj_rest_auth</em></strong> has basic auth functionality like login, logout, password reset and password change</li><li><strong><em>dj_rest_auth.registration</em></strong> has logic related with registration and social media authentication</li></ul><p>The second sub app is optional but we will install it to have the registration features.</p><p>Given all that information, and as indicated in the dj-rest-auth installation documentation, we have to install the right packages (to add in <em>requirements.txt</em>) and add the proper apps to INSTALLED_APPS in <em>settings.py</em>.</p><p>First let’s add these two dependencies in our requirements.txt:</p><ul><li><em>djangorestframework</em></li><li><em>dj-rest-auth[with_social]</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*LhQM5h9VDow2PbJ1xfoCcg.png" /></figure><p>Do not forget to rebuild your image (“docker-compose build”).</p><p>Then let’s add the following apps to INSTALLED_APPS:</p><ul><li>“django.contrib.sites”</li><li>“rest_framework”</li><li>“rest_framework.authtoken”</li><li>“allauth”</li><li>“allauth.account”</li><li>“allauth.socialaccount”</li><li>“dj_rest_auth”</li><li>“dj_rest_auth.registration”</li></ul><p>A few additional settings are needed.</p><p>First, add <em>SITE_ID = 1</em> at the bottom of your django <em>settings.py</em>.</p><pre>SITE_ID = 1</pre><p>Then, add the required <em>allauth.account.middleware.AccountMiddleware</em> into our <em>settings.py</em>, into the MIDDLEWARE list.</p><pre>MIDDLEWARE = [<br>    &quot;django.middleware.security.SecurityMiddleware&quot;,<br>    &quot;django.contrib.sessions.middleware.SessionMiddleware&quot;,<br>    &quot;django.middleware.common.CommonMiddleware&quot;,<br>    &quot;django.middleware.csrf.CsrfViewMiddleware&quot;,<br>    &quot;django.contrib.auth.middleware.AuthenticationMiddleware&quot;,<br>    &quot;django.contrib.messages.middleware.MessageMiddleware&quot;,<br>    &quot;django.middleware.clickjacking.XFrameOptionsMiddleware&quot;,<br>    &quot;allauth.account.middleware.AccountMiddleware&quot;,  # Third-party<br>]</pre><p>Then, we need to configure several urls for <em>dj-rest-auth</em> (in “app &gt; api_v1 &gt; urls.py”).</p><pre>...<br><br>urlpatterns = [<br> path(&quot;dj-rest-auth/&quot;, include(&quot;dj_rest_auth.urls&quot;)),<br> path(<br> &quot;dj-rest-auth/registration/&quot;,<br> include(&quot;dj_rest_auth.registration.urls&quot;),<br> ),<br>]</pre><p>Now if you try to start the app, it should fail, complaining about the fact that “<em>User has no field named ‘username’</em>”. The reason is that we implemented our custom user model and added no <em>username</em> field to that model.</p><p>So we need to tell <em>django-allauth</em> (which is used behind the scenes by dj-rest-auth) that we do not have a <em>username</em> field. And we will also let it know that we want to use the <em>email</em> field instead for the authentication.</p><p>In the <em>settings.py</em>, we need to put the following configuration lines (you can take a look <a href="https://docs.allauth.org/en/latest/account/advanced.html">here</a> if you wanna learn more).</p><pre># django-allauth configurations so that dj-rest-auth uses email for<br># login/registration and does not require a username field<br>ACCOUNT_AUTHENTICATION_METHOD = &quot;email&quot;<br>ACCOUNT_USERNAME_REQUIRED = False<br>ACCOUNT_EMAIL_REQUIRED = True<br>ACCOUNT_UNIQUE_EMAIL = True<br>ACCOUNT_USER_MODEL_USERNAME_FIELD = None</pre><p>With these configurations done, you should be able to start your application successfully.</p><p>Note that some migrations will be applied. They are related to dj-rest-auth and its dependencies. By the way, you should notice several new sections in the Home of the Django admin site.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sujV0MFhFcpmbLW49pNOYA.jpeg" /></figure><p>In this part, we will use <em>drf-spectacular</em> to extract schema information from Django REST framework, generate an OpenAPI schema, and enable a Swagger UI to visualize our API endpoints.</p><p>Firstly, we need to update the <em>requirements.txt</em> file to add drf-spectacular, and execute “docker-compose build” to rebuild our docker image.</p><pre>drf-spectacular&gt;=0.27.2,&lt;0.28</pre><p>Second, in Django <em>settings.py</em>, we must:</p><ul><li>Add “drf_spectacular” to INSTALLED_APPS</li><li>Add the needed REST_FRAMEWORK configuration property in order to tell Django to use the openapi schema generation class provided by drf-spectacular to generate the schema of our API</li></ul><pre>INSTALLED_APPS = [<br>    …<br>    # Third-party apps<br>    …<br>    &quot;drf_spectacular&quot;,<br>]<br><br>…<br><br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_SCHEMA_CLASS&#39;: &#39;drf_spectacular.openapi.AutoSchema&#39;,<br>}</pre><p>Finally, we have to enable the URLs that are needed in order to serve the documentation through our Django project.</p><p>We will do that in the “app &gt; api &gt; urls.py” file, considering that the documentation should be put aside from the actual “data-related” api endpoints.</p><pre>from django.urls import path, include<br><br>from drf_spectacular.views import (<br>    SpectacularAPIView,<br>    SpectacularSwaggerView,<br>)<br><br>urlpatterns = [<br>    path(&quot;schema/&quot;, SpectacularAPIView.as_view(), name=&quot;api-schema&quot;),<br>    path(<br>        &quot;docs/&quot;,<br>        SpectacularSwaggerView.as_view(url_name=&quot;api-schema&quot;),<br>        name=&quot;api-docs&quot;,<br>    ),<br>    path(&quot;v1/&quot;, include(&quot;api_v1.urls&quot;)),<br>]</pre><p>Now, if you start your services and browse to <em>http://localhost:8000/api/docs/</em> in your browser, you should see something similar to the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDmTZZRh6oD5FpxN-Rfjqg.png" /></figure><p>You can see a GET endpoint under <em>/api/schema/</em>. This is where drf-spectacular exposes the schema information that it extracted from our project. This is consumed in order to generate this clean Swagger UI we browsed to.</p><p>Under this endpoint you can see all our enabled dj-rest-auth endpoints, for many authentication features like login/logout, registration, and password change/reset.</p><p>Note, that dj-rest-auth also provides three endpoints to interact with user data: a GET endpoint to retrieve user data and a PUT and PATCH endpoints to update user data.</p><p>Pretty neat huh? 😎</p><p>But, if you look more closely at the endpoints for user registration and for user retrieval/update, you will notice that something is odd.</p><p>For example, for the GET user endpoint the response format indicated by the Swagger UI shows a <em>pk</em> (for primary key) and an <em>email</em> fields, whereas we would prefer:</p><ul><li>Not to return <em>pk</em></li><li>Return the missing <em>name</em> field</li></ul><p>Similarly, in the PUT endpoint, the request body example is empty. We want to be able to update the user email, name and password.</p><p>We will fix that in the next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUUXATbh0CxjKn9VS70W4A.jpeg" /></figure><p>First, we will fix the user endpoints.</p><p>If you remember, in the <a href="https://medium.com/@CodeUmwelt/django-rest-api-with-custom-user-model-jwt-cookie-authentication-custom-django-user-model-7b5a697665de">4th article</a>, we implemented a custom user serializer. We will now let Django REST framework know that we want to use this serializer for our user endpoints.</p><p>For that, go to <em>settings.py</em> and add the following settings (check <a href="https://dj-rest-auth.readthedocs.io/en/latest/configuration.html#user-details-serializer">dj-rest-auth documentation</a> if you are curious).</p><pre>REST_AUTH = {<br>    &quot;USER_DETAILS_SERIALIZER&quot;: &quot;user.serializers.UserSerializer&quot;,<br>}</pre><p>If you now refresh the Swagger UI, you will see the updates reflected in the dj-rest-auth GET, PUT and PATCH user endpoints.</p><p>We also want to fix the dj-rest-auth endpoint for user registration (POST — <em>/api/v1/dj-rest-auth/registration/</em>). To do that, we will proceed a similar way as we did for user endpoints.</p><p>First we will implement a custom register serializer and then plug it in dj-rest-auth settings. In “app &gt; user &gt; serializers.py”, add the following code.</p><pre>…<br>from django.db import transaction<br><br>…<br>from dj_rest_auth.registration.serializers import RegisterSerializer<br><br>…<br>class CustomRegisterSerializer(RegisterSerializer):<br>    &quot;&quot;&quot;Custom serializer for user registration.&quot;&quot;&quot;<br><br>    name = serializers.CharField(max_length=255)<br><br>    # Define transaction.atomic to rollback the save operation in case of error<br>    @transaction.atomic<br>    def save(self, request):<br>        user = super().save(request)<br>        user.name = self.data.get(&quot;name&quot;)<br>        user.save()<br>        return user</pre><p>In <em>settings.py</em>, add the following setting.</p><pre>REST_AUTH = {<br>    &quot;REGISTER_SERIALIZER&quot;: &quot;user.serializers.CustomRegisterSerializer&quot;,<br>    …<br>}</pre><p>After you refresh the Swagger UI, you will see that the <em>name</em> field now appears in the request body example for the “POST — <em>api/v1/dj-rest-auth/registration/</em>” endpoint.</p><p>For the registration process, dj-rest-auth (through Django allauth) also provides an email address confirmation feature. We can select the value of the ACCOUNT_EMAIL_VERIFICATION setting, to allow one of three behaviors as explained in <a href="https://docs.allauth.org/en/latest/account/configuration.html">Django allauth documentation</a>:</p><ul><li>“optional” (the default value — email verification email is sent but user can login without verifying her/his email address)</li><li>“mandatory” (email verification email is sent and user cannot login without verifying her/his email address)</li><li>“none” (email verification email is not sent, and user can login)</li></ul><p>We will use the “mandatory” option.</p><p>And in order to receive the email verification email, even if we did not set any email server, we will use some email backend facility from Django to see the email in the console logs.</p><pre>ACCOUNT_EMAIL_VERIFICATION = &quot;mandatory&quot;<br>EMAIL_BACKEND = &quot;django.core.mail.backends.console.EmailBackend&quot;</pre><p>Because we set account email verification as mandatory, we need to add a path to our urls (in “app &gt; api_v1 &gt; urls.py”) that will be used by the verification view.</p><pre>...<br>from dj_rest_auth.registration.views import VerifyEmailView<br>...<br>urlpatterns = [<br>    ...<br>    path(<br>        &#39;dj-rest-auth/account-confirm-email/&#39;,<br>        VerifyEmailView.as_view(),<br>        name=&#39;account_email_verification_sent&#39;<br>    ),<br>    ...<br>]</pre><p><strong><em>Note:</em></strong> at this point, if you have separate front end and back end (for example when using a SPA on the front end, with frameworks like Angular or React), you may have to customize the URL that is provided by dj-rest-auth in the email verification email sent to the user. This is because in that situation, the user will probably access you front end for email confirmation, and your front end might be hosted on a different domain than your backend. We won’t do that here, but I’ll try to write a future article on that, where I’ll explain how to implement an Angular front end to interact with the REST API we’re currently implementing.</p><p>Ok, let’s quickly test the registration process.</p><p>Go to the Swagger UI and deploy the section for the “POST — <em>api/v1/dj-rest-auth/registration/</em>” endpoint.</p><p>Click the “Try it out” button. You can now update the request body with user registration information. When you’re done, click on “Execute” to launch the request to the REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hiqbbf8r_Xvx8s5jeVthGQ.png" /></figure><p>You should receive an <em>HTTP 201 CREATED</em> response. The user record will be created in the database and the email verification email will be logged to your console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*82katmdiv5fEDoPFvMTRgQ.png" /></figure><p>If you open the Django admin site, you should see a notification telling you that confirmation email has been sent to your user email address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*DcuRbCcZLvxNEjlN0VlnFQ.png" /></figure><p>If you check the user records, you should see your new user alongside your previously created admin user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdjYdBC_Dpg1tDxoVODsPQ.png" /></figure><p>If you click on the “Email addresses” button, you should see that a record has been saved for your new user’s email address. You should also notice that the “verified” field is set to false, which confirms that your new user’s email address has not been confirmed yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WulNnJ-RbAzULQrAFCjRUw.png" /></figure><p>If you tried to login as this user now, it would fail (since we configured the email address verification as “mandatory”). So let’s confirm this email address.</p><p>You can copy the key located at the end of the URL sent in the email verification email (see your Django application logs), and use it in the request body of the “POST — <em>/api/v1/dj-rest-auth/registration/verify-email/</em>” endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsAN6xTmq2s7CyDMcU1grQ.png" /></figure><p>You should receive an <em>HTTP 200 OK</em> response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*03M8zpj4rF1bXm6v4_n74Q.png" /></figure><p>And if you go back to the admin console, you should see that the email address has been verified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGIj8lS6ZcF_6qG8qEWE0g.png" /></figure><p>So let’s try to login now. Use the “POST — <em>/api/v1/dj-rest-auth/login/</em>” endpoint for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NTC9KrzSitiXCyLf8YTcsQ.png" /></figure><p>Once you’ve executed the request, you should receive an <em>HTTP 200 OK</em> response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QjbX8RADrGFxVmVupP9Iow.png" /></figure><p>Remember here that we still have the default Django “session” authentication method, not JWT cookie authentication yet. If you check the developer tools of your browser, you should have a new <em>sessionid</em> cookie for your user session.</p><p>Now that you are logged in, you can use the user endpoints provided by dj-rest-auth, e.g. the “GET —<em> /api/v1/dj-rest-auth/user/</em>” endpoint to retrieve the info for a user. If you had tried it before logging in, you would have received an <em>HTTP 401 UNAUTHORIZED</em> response.</p><p><strong><em>Note #1:</em></strong> If you try to access the Django admin site in the same browser, and you previously had a session with an admin user ongoing, you will be logged out, as the regular user session overrode it.</p><p><strong><em>Note #2:</em></strong> You might have noticed a “key” field in the body of the <em>HTTP 200 OK</em> response to the login request. This is actually a “token” generated by dj-rest-auth as part of its default authentication method: the Django Token-based authentication method. You can see another trace of this in the admin console, where you can see that an “AUTH TOKEN” section appears, with “Tokens” records below. So, the key you see in the login HTTP response is dj-rest-auth returning an authentication token upon successful login. But our application is not configured to use this auth method yet. So as it is, this token is useless. If you wanted to be able to use this auth method as an additional option, in parallel of the default session authentication method, you could configure your project to do so, by adding the following settings in <em>settings.py</em>.</p><pre>REST_FRAMEWORK = {<br>    …<br>    &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: [<br>        &quot;rest_framework.authentication.TokenAuthentication&quot;,<br>    ],<br>}</pre><p>We won’t do that since we don’t wanna use this basic Django Token authentication method as it is.</p><p>You could even disable the default session authentication method for dj-rest-auth, by adding the following to <em>settings.py</em>. When done, your browser would not set any <em>sessionid</em> cookie anymore upon successful call to the login endpoint. Note that this is a dj-rest-auth specific setting, so you would still be able to login to the Django admin site, which uses Django’s default session authentication method.</p><pre>REST_AUTH = {<br>    &quot;REGISTER_SERIALIZER&quot;: &quot;user.serializers.CustomRegisterSerializer&quot;,<br>    &quot;USER_DETAILS_SERIALIZER&quot;: &quot;user.serializers.UserSerializer&quot;,<br>    &quot;SESSION_LOGIN&quot;: False,<br>}</pre><p>We will apply this “SESSION_LOGIN” configuration, because we have tested above that the main authentication features are working, and we won’t need session authentication on our REST API later since we will enable “JWTCookieAuthentication” from dj-rest-auth.</p><p><strong><em>Note #3:</em></strong> A bit earlier, we said we could customize the email verification url, which could be especially useful when using a separate SPA front end. Actually, we can do a similar customization for the password reset url. But I’ll write about that in a future article 😉</p><p>Wow! That was quite a lot of things to do 🥵</p><p>I hope you’re still here with me.</p><p>If you do, I want to congratulate you! ✨ 🙌 ✨</p><p>Take a deep breath as we’re about to go through the last part of the last article of this series of articles about implementing a Django REST API with JWT HttpOnly &amp; Secure Cookies!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1eNlsEORaGwyedrMVu8aw.jpeg" /></figure><p>Firstly, I encourage you to read/learn a bit about JWT:</p><ul><li>What it is, and what it is not</li><li>Why it is controversial among developers</li><li>Pros and cons of its usage</li><li>…</li></ul><p>You can find plenty of resources on the web, but try to stick to content that:</p><ul><li>Comes from reliable/trustworthy sources</li><li>Is as much recent as possible</li></ul><p>For example, regarding the topic of JWT in authentication, I believe <a href="https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html">this page</a> from the OWASP and <a href="https://blog.angular-university.io/angular-jwt-authentication/">this other page</a> are relevant.</p><p>Having read on that topic, you will probably understand that the implementation we are covering here is not flawless in terms of cybersecurity.</p><p>Unfortunately, in this domain, there’s no magical solution that fits every context. Moreover, you will almost always have to do design choices based on <strong><em>security</em></strong> vs <strong><em>implementation convenience</em></strong> vs <strong><em>performance</em></strong> vs <strong><em>user experience</em></strong> tradeoffs.</p><p>So, I encourage you to learn as much as possible, in order to implement what you will feel is the best solution for your specific context, in particular when talking about applications that are in production, that are consumed by many users, and even more if sensitive information is at stake.</p><p>Ok, that being said, let’s configure JWT cookie authentication. Most of the configurations mentioned below come from the <a href="https://dj-rest-auth.readthedocs.io/en/latest/installation.html#json-web-token-jwt-support-optional">dj-rest-auth installation documentation</a>.</p><p>For JWT support, dj-rest-auth depends on the <strong><em>djangorestframework-simplejwt</em></strong> library, so we must add it to our <em>requirements.txt</em> file.</p><pre>djangorestframework-simplejwt&gt;=5.3.1,&lt;5.4</pre><p>Once done, make sure your services are down, and try a “docker-compose build”. It should run successfully.</p><p>Then, set the proper authentication class for Django REST framework, in your <em>settings.py</em>.</p><pre>REST_FRAMEWORK = {<br>    …<br>    &quot;DEFAULT_AUTHENTICATION_CLASSES&quot;: [<br>        &quot;dj_rest_auth.jwt_auth.JWTCookieAuthentication&quot;,<br>    ],<br>}</pre><p>Then, still in <em>settings.py</em>, add the following dj-rest-auth settings:</p><ul><li><strong><em>USE_JWT</em></strong> set to <em>True</em>. This is to use JWT authentication instead of Token or Session based authentication</li><li><strong><em>JWT_AUTH_COOKIE</em></strong> and <strong><em>JWT_AUTH_REFRESH_COOKIE</em></strong> to set a custom name for the access token and the refresh token respectively</li><li><strong><em>JWT_AUTH_SECURE</em></strong> to <em>True</em>. This is to tag the cookie as “<a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#block_access_to_your_cookies">Secure</a>”, which means it will only be sent over HTTPS connections</li><li><strong><em>JWT_AUTH_HTTPONLY</em></strong> to <em>True</em>. This is the default value but we want to set it explicitly here. This will prevent client-side JavaScript code from accessing the cookie. Note that the refresh token will not be sent in the response body if <em>JWT_AUTH_HTTPONLY</em> is set to <em>True</em> (which is normal since we want to prevent access from JavaScript code)</li></ul><pre>REST_AUTH = {<br>    …<br>    &quot;USE_JWT&quot;: True,<br>    &quot;JWT_AUTH_COOKIE&quot;: &quot;jwt-access-token&quot;,<br>    &quot;JWT_AUTH_REFRESH_COOKIE&quot;: &quot;jwt-refresh-token&quot;,<br>    &quot;JWT_AUTH_SECURE&quot;: True,<br>    &quot;JWT_AUTH_HTTPONLY&quot;: True,  # True is the default value<br>}</pre><p>If you start your services and access the Swagger UI (at <em>http://localhost:8000</em>), you should now see two additional endpoints for token refresh and token verification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_erBTiYSl3YqaskV3bTgSw.png" /></figure><p>Also if you try to login again, you should receive a response similar to the following one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1nwtuj4X31RV7DcfzGv4g.png" /></figure><p>And if you access your browser developer tools, you will notice that the access and refresh tokens have been set as cookies, both with the <em>Secure</em> and <em>HttpOnly</em> flags.</p><p>Note that the refresh token has a much longer life duration compared to the access token. This is because it is used to request a new access token whenever the access token has expired. When the refresh token expires, you have to log in again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXPnRbFz4LkwBuoBv6y3bA.png" /></figure><p>You can add a small but useful additional configuration to secure your project a bit more. I let you check it <a href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/settings.html#signing-key">here</a>.</p><p>The idea is that if, for one reason or another, someone manages to discover the key used to sign your JWTs, by default this person will know your Django <em>SECRET_KEY</em> too.</p><p>This is because they are the same by default.</p><p>Having to change the <em>SECRET_KEY</em> of a Django project can be quite annoying. So you might rather set a different (and strong) signing key for your tokens, by using the “SIGNING_KEY” setting exposed by the <em>djangorestframework-simplejwt</em> library in your <em>settings.py</em> file.</p><p>Ok, we’re done with these configurations.</p><p>Now if you implement business-specific REST API endpoints, do not forget to set <em>JWTCookieAuthentication</em> as the authentication class for the corresponding Django views. For example, for Django REST framework class-based views, you can set <em>authentication_classes = [JWTCookieAuthentication]</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NkdxCf-UKTY_xsWRvo0MA.jpeg" /></figure><p>Lastly, do a quick git commit to save your code state and push it to your GitHub repository.</p><pre>git add .<br>git commit -m &quot;jwt cookie authentication&quot;<br>git push origin main</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S01Tl8Ez2M-GQPWe-VrnLw.jpeg" /></figure><p>Well, I guess that’s all for this series of articles guys.</p><p>Note that we played with our REST API from the Swagger UI, which is hosted on the same <em>protocol+domain+port</em> combination as our REST API itself. So we did not have to bother about some other configurations, like CORS settings or HTTPS activation for example.</p><p>If you want to use a separated front end application (e.g. an Angular or React SPA), hosted at a different origin, to consume your back end REST API, then you’ll have to go through all these settings.</p><p>But that will be for another series of articles. For now, you’ve already worked enough! 😁</p><p>I really want to congratulate you for making it until the end!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*8zutjnye43FjJjAXtk0wyg.gif" /></figure><p>I hope you learned many things, and more importantly that you enjoyed it and now take proud out of it 💪</p><p>Writing this series of articles took quite some time. So if you enjoyed it, do not hesitate to let me know, clap, share, or do whatever positive thing you can think of from this 😉👍</p><p>You can also follow me on Medium.</p><p>Thanks a lot for taking the time to read me until there!</p><p>See ya in a future article! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b33076c4b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>