[PYTHON] Easy user authentication and token authentication with djangorestframework-jwt

I'm a Chinese developer. He had worked in Hamamatsucho, Tokyo for about a year. Nice to meet you.

Introducing djangorestframework-jwt

djangorestframework-jwt is a Django package that makes user authentication and token authentication easy.

This article will show you how to make an API using djangorestframework-jwt.

environment OS:Win10 or CentOS Python:3.7 Django:3.1.2

Installation

You need these two lilibrari.

$ pip install djangorestframework

$ pip install djangorestframework-jwt

coating

① Modify or add these codes to settings.py

settings.py


import datetime

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',  # <--to add
    'my_app'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',  <--To comment
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

#Framework for authentication
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated'
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication'
    )
}

JWT_AUTH = {
    #Set the token validity time
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=60 * 60 * 2)
}

② Insert the code in urls.py

There are two APIs here.

  1. userLogin is an API for user registration and authentication. The front end is an API that sends the user name and password to the back end by POST, registers it, and then obtains the token. (You can use the django admin superuser as the user and password.)

  2. getInfo is an API that acquires information using tokens after user registration.

urls.py


from django.urls import path
from my_app import views

urlpatterns = [
    path('userLogin/', views.user_login),
    path('getInfo/', views.get_info)
]

③ Insert the code in views.py

views.py


import json
from django.http import JsonResponse
from django.contrib.auth import authenticate, login
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework_jwt.settings import api_settings


def user_login(request):
    obj = json.loads(request.body)
    username = obj.get('username', None)
    password = obj.get('password', None)

    if username is None or password is None:
        return JsonResponse({'code': 500, 'message': 'Number of requests'})

    is_login = authenticate(request, username=username, password=password)
    if is_login is None:
        return JsonResponse({'code': 500, 'message': 'Password or password'})

    login(request, is_login)

    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(is_login)
    token = jwt_encode_handler(payload)

    return JsonResponse(
        {
            'code': 200,
            'message': 'Successful registration',
            'data': {'token': token}
        }
    )


#Grant token authentication to API
@api_view(['GET'])
@permission_classes((IsAuthenticated,))
@authentication_classes((JSONWebTokenAuthentication,))
def get_info(request):
    data = 'some info'

    return JsonResponse(
        {
            'code': 200,
            'message': 'success',
            'data': data
        }
    )

How the front end uses the API

First, use userLogin in POST to get a token.

Next, use getInfo with Get and specify JWT + the token obtained earlier in the Authorization parameter of Headers to request.

Front end example


token = 'abcdefg123456789'

authorization = 'JWT' + token

This will allow getInfo to be requested.

Recommended Posts

Easy user authentication and token authentication with djangorestframework-jwt
Easily create authentication, user management, and multilingual systems with Flask-AppBuilder
Easy Slackbot with Docker and Errbot
Authentication process with gRPC and Firebase Authentication
Basic authentication and Digest authentication with Flask
Firebase Authentication token issuance in Python and token verification with Fast API
Passwordless authentication with RDS and IAM (Python)
Easy web scraping with Python and Ruby
Django: Record User Agent and manage with Admin
Easy X-Ray with Lambda Layer and CloudFormation / sam-cli
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 6] ~ User Authentication 2 ~
Let's make a nervous breakdown application with Vue.js and Django-Rest-Framework [Part 5] ~ User authentication ~
More new user authentication methods with Django REST Framework
Easy IoT to start with Raspberry Pi and MESH
Easy machine learning with scikit-learn and flask ✕ Web app
Easy partial download of mp4 with python and youtube-dl!
Create APIs around user authentication with Django REST Framework
Easy face recognition try with Jetson Nano and webcam
[Python] Get user information and article information with Qiita API
Easy debugging with ipdb
With and without WSGI
Easy TopView with OpenCV
I tried follow management with Twitter API and Python (easy)
Create an authentication feature with django-allauth and CustomUser in Django