commonly Django Development to protect against csrf The attack of , If you use Django Template rendering page for , Then you can render and set a csrftoken Of cookie data , But if you need to separate the front and back , Do not apply Django Template rendering function of , How to access dynamically csrftoken Well ? ”
from django.middleware.csrf import get_token def getToken(request): token=get_token(request) return HttpResponse(json.dumps({'token':token}), content_type="application/json,charset=utf-8")
In this way, you can get csrftoken The data of , Let's write an example to demonstrate .
views.py
Set up getToken Method from django.middleware.csrf import get_token # obtain cstftoken def getToken(request): token = get_token(request) return HttpResponse(json.dumps({'token': token}), content_type="application/json,charset=utf-8")
urls.py
To configure URLfrom django.urls import path, re_path from . import views urlpatterns = [ # ex:/assetinfo/getToken path('getToken', views.getToken, name='getToken'), ... ]
postman
Test interface , obtain csrftokenimage-20200601155201234
Now it's time to complete the basic functions , Can we get it dynamically csrftoken, But there is also a cross domain problem , If you can't get it after cross domain csrftoken 了 .
I've tried in Django Set the cross domain return method in , But it's not going to work , Because different domain names use csrftoken Basically lost the original prevention csrf The meaning of the attack .
The best way is to use nginx Acting as a local agent , Reverse proxy front end respectively 、 Back end services , Then provide a unified domain name to use , You can use csrftoken 了 .
When you want to postman Use in csrftoken, So just take what you get csrftoken The value is set to Headers Then you can , as follows :
image-20200602112047276
{"X-CSRFToken":"K6q7uqt9J8UocELWR04pw2DKd8T2LRNWjf2uQvsFBWm87Q1lJZQV1vj3pR8REzCR"}
If not set , Then there will be 403 False report rejection as follows :
image-20200602112127065
This article is from WeChat official account. - Fisherman of the sea (DevOpsFreshMan) , author :Devops Fisherman of the sea
The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .
Original publication time : 2020-11-11
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .