We're going to take you step-by-step to build a fully functional open-source JWT Authentication REST API using Python, Django Rest Framework.
You can view all the dependencies from the requirements.txt file.
-
Navigate to your workspace and create a virtual environment with
python -m venv env
-
Activate the virtual environment
-
Linux: Activate the virtual environment run:
source .env/bin/activate
-
Windows: Activate the virtual environment run:
env\Scipts\activate
-
-
Install the following project dependencies run:
pip install Django==4.2.6 pip install djangorestframework==3.14.0 pip install PyJWT==2.7.0
-
After the installation is complete let's create our django project, we are going to call our project core run:
django-admin startproject core
. Let’s look at what startproject created:core/ manage.py core/ __init__.py settings.py urls.py asgi.py wsgi.py
-
After the creation of the project, let's create an app called users. First you need to
cd
to the created project which is named core and run:django-admin startapp users
. The application will be created inside the Django project core. Let's look at the folder structure below.core/ manage.py core/ __init__.py settings.py urls.py asgi.py wsgi.py users/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py
-
Navigate to
settings.py
and update the following:INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', # NEW SET UP FOR DJANGO REST FRAMEWORK 'users', # NEW ADD USERS APP IN THE INSTALLED APPS ] # NEW ADD ALL OF THIS REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'users.authentication.backends.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], }
-
Let's create a file in the following directory in the users app /users/authentication/backends.py. If you don't have the authentication/ you MUST create it and also in the authentication folder add
__init__.py
file to make the module accessible. -
The following code implements the JWT middleware
-
After that you need to run migrations to create the migration files run:
python manage.py makemigrations
-
To apply the migrations and create the tables in the database run:
python manage.py migrate
-
If you want to test the application you will find the tests at users/tests.py run tests:
python manage.py tests
-
run the application
manage.py runserver