I'm a Chinese developer. He had worked in Hamamatsucho, Tokyo for about a year. Nice to meet you.
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
You need these two lilibrari.
$ pip install djangorestframework
$ pip install djangorestframework-jwt
① 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.
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.)
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
}
)
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