Relevant chapters

Django 2.1.7 Creating an Application Template

Django 2.1.7 Configures public Static files, public template paths

Django 2.1.7 Template Language – Variables, tags, filters, custom filters, template comments

Django 2.1.7 Template Inheritance

Django 2.1.7 Template-HTML escape

reference

Docs.djangoproject.com/zh-hans/2.1…

CSRF

CSRF stands for Cross Site Request Forgery. CSRF is when an attacker steals your identity and sends malicious requests on your behalf. CSRF can do things like: send emails in your name, send messages, steal your account, even buy goods, virtual currency transfer…… The problems include personal privacy leakage and property security.

The SCHEMATIC diagram of CSRF is as follows:

If you want to prevent CSRF, first of all, important messages are sent using POST rather than GET. Then we’ll discuss how to attack POST requests and how to avoid them in Django.

The sample

Let’s start two Django services to simulate the attack.

Start by building your first Django project

1) Open the assetinfo/views.py file and create views login, login_check, POST and post_action.

def login(reqeust):
    return render(reqeust, 'assetinfo/login.html')

def login_check(request):
    username = request.POST.get('username') Get user name
    password = request.POST.get('password') Get password

    # check
    if username == 'smart' and password == '123':
        request.session['username'] = username Remember the login user name
        request.session['islogin'] = True Check whether the user is logged in
        return redirect('/assetinfo/post/')
    else:
        return redirect('/assetinfo/login/')

def post(request):
    return render(request, 'assetinfo/post.html')

def post_action(request):
    if request.session['islogin']:
        username = request.session['username']
        return HttpResponse('users'+username+'Posted a post')
    else:
        return HttpResponse('Post failed')
Copy the code

2) Open the assetinfo/urls.py file and configure the URL.

urlpatterns = [
    # ex:/assetinfo/login
    path('login/', views.login),
    # ex:/assetinfo/login_check
    path('login_check/', views.login_check),
    # ex:/assetinfo/post
    path('post/', views.post),
    # ex:/assetinfo/post_action
    path('post_action/', views.post_action),
]
Copy the code

3) Create login. HTML and post.html in the templates/assetinfo/ directory.

login.html

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title> User login </title> </head> <body> <form method="post" action="/assetinfo/login_check/"> User name: <inputtype="text" name="username"/><br/> Password: <inputtype="password" name="password"/><br/>
    <input type="submit" value="Submit"/>
</form>
</body>
</html>
Copy the code

post.html

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title> </head> <body> <form method="post" action="/assetinfo/post_action/"> title: < inputtype="text" name="title"/><br/> contents :<textarea name="content"></textarea>
    <input type="submit" value="Post"/>
</form>
</body>
</html>
Copy the code

4) Start the server.

python3 manage.py runserver
Copy the code

5) Type the following url into your browser and call this TAB Website A.

http://127.0.0.1:8000/assetinfo/login/

The browsing effect is as follows:

Enter your account and password, log in, and enter the Posting page as follows:

6) using the Django below the second project to simulate another web site, to create a post, HTML, copy the templates/assetinfo/post. The HTML content, and modify the action.

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"</title> </head> <body> <form method="post" action="http://127.0.0.1:8000/assetinfo/post_action/"> title: < inputtype="text" name="title"/><br/> contents :<textarea name="content"></textarea>
    <input type="submit" value="Post"/>
</form>
</body>
</html>
Copy the code

7) View the effect in the Windows browser as shown below. Call this label website B.

8) CSRF protection is enabled by default in Django projects. To disable it, open the mysite/settings.py file in the first Django project and comment out the CSRF middleware.

9) Click the first TAB of the browser, i.e. website A, and click the “Post” button as shown below:

10) Click the second TAB of the browser, namely website B, and click the “Post” button as shown below:

Use action to directly access the address of website A and successfully execute the post.

Comparing the previous two steps, it is not safe to access the post_action view of site A from either site A or site B.

Prevent CSRF

1) Django provides CSRF middleware to protect against CSRF attacks. Just enable the CSRF middleware in mysite/settings.py on site A.

Note that Django 2 doesn’t start MIDDLEWARE in MIDDLEWARE_CLASSES by default. Instead, it starts MIDDLEWARE in MIDDLEWARE_CLASSES, as follows:

MIDDLEWARE = (
    'django.contrib.sessions.middleware.SessionMiddleware'.'django.middleware.csrf.CsrfViewMiddleware'.)Copy the code

2) Go back to Windows browser and click the “Submit” button in website A and website B respectively, with the same effect as shown in the picture below:

3) this trouble, because the site may not be able to access, the following templates/assetinfo/post. The HTML content, using the tag in the form form csrf_token.

{% csrf_token %}
Copy the code

4) Go back to Windows Browser and click “Submit” button in website A. The effect is as follows:

5) Go back to Windows browser and click “Submit” button in website B. The effect is as follows:

That’s it. CSRF protection in Django is complete.

conclusion

  • Important information, such as amount and points, will be delivered by POST
  • Enable CSRF middleware. This function is enabled by default
  • Add the label CSRF_Token to the form when post is submitted

Protection principle

After the tag is added, you can look at the post.html source code and see that there is an additional hidden field.

View cookie information in developer Tools of your browser.

Description: When the middleware is enabled and the tag CSRF_Token is added, a Cookie message will be written to the browser of the client. The value of this message is consistent with the value attribute of the input element of the hidden field. After being submitted to the server, it will be verified by the CSRF middleware. There is no subsequent processing.