Article Directory
Django rest framwork jwt
http://jpadilla.github.io/django-rest-framework-jwt/
1. Installation
Note: switch to the Python environment of your own project to install
$ pip3 install djangorestframework-jwt
2. Use
2.1 Use of global settings
In settings.py
added JSONWebTokenAuthentication
to Django REST framework DEFAULT_AUTHENTICATION_CLASSES
.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
In urls.py
the Add the following URL routing, which can enable the function to get the user token via POST requests, the need to provide the user name and password when sending a POST request.
2.2 View settings and use
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
class UsersSeriaView(APIView):
authentication_classes = [JSONWebTokenAuthentication]
permission_classes = [IsAuthenticated]
Configure URL
from rest_framework_jwt.views import obtain_jwt_token
#...
urlpatterns = [
'',
# ...
path(r'api-token-auth/', obtain_jwt_token),
]
Set Tocken valid time and prefix of authentication token information
In the settings.py
settings file
import datetime
JWT_AUTH = {
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
}
postman tool
Create postman request
Get token
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNTY5MTQ3MzgzLCJlbWFpbCI6ImFkbWluQHNoYXJrLmNvbSJ9.v5t9lr2zEnI0nlTfTl3FRdHMmiEMBO1Mwp5zQV6i5kY
Use JWT token
curl tool
If you create a user with the username admin and password password123, you can easily test whether the endpoint is working properly by performing the following operations in the terminal.
$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/
Submit in JSON format
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/
Then you can use Token to get the corresponding data
$ curl -H "Authorization: JWT <your_token>" http://localhost:8000/protected-url/