Skip to content

jwt

Example

pip install django

pip install djangorestframework-simplejwt

# env
pip install python-dotenv

# database
pip install mysqlclient

# Django REST framework
pip install djangorestframework, markdown, django-filter
INSTALLED_APPS = [
    ...'
    'rest_framework',
    'rest_framework_simplejwt',
    ...
]
$ python -m venv venv
$ cd venv/Scripts
$ activate
# settings.py
from dotenv import load_dotenv
import os

load_dotenv()

SECRET_KEY = os.environ.get('SECRET_KEY')

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ.get('DB_NAME'), #here
        'USER': os.environ.get('DB_USER'), #here
        'PASSWORD': os.environ.get('DB_PASS'), #here
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"},
    }
}

# Add
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
}
SECRET_KEY=""
DB_NAME=django_db
DB_USER=root
DB_PASS=
DB_HOST=localhost
DB_PORT=3308

Simple JWT

Simple JWT provides a JSON Web Token authentication backend for the Django REST Framework. A JSON Web Token authentication plugin for the Django REST Framework.

Installation

pip install djangorestframework-simplejwt

Tip

# add rest_framework_simplejwt to INSTALLED_APPS.

INSTALLED_APPS = [
    ...
    'rest_framework_simplejwt',
    ...
]

Project Configuration

Then, your django project must be configured to use the library. In settings.py, add rest_framework_simplejwt.authentication.JWTAuthentication to the list of authentication classes:

Tip

REST_FRAMEWORK = {
    ...
    'DEFAULT_AUTHENTICATION_CLASSES': (
        ...
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
    ...
}

Also, in your root urls.py file (or any other url config), include routes for Simple JWT’s TokenObtainPairView and TokenRefreshView views:

Tip

from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    ...
]

Reference