SoFunction
Updated on 2024-11-16

Python djanjo csrf anti cross-site attack experimental process

I. Introduction to CSRF

  1. What is CSRF?
    CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also known as: one click attack/session riding, abbreviated as: CSRF/XSRF.
  2. What can CSRF do?
    You can understand CSRF attack in this way: the attacker steals your identity and sends a malicious request in your name. CSRF can do things including: send emails in your name, send messages, steal your account, and even buy goods, virtual currency transfers ... The problems caused by the leakage of personal privacy and property security.
  3. Status of CSRF vulnerabilities?
    CSRF this attack has been proposed by foreign security personnel in 2000, but in the country, until 2006 only began to be concerned about, in 2008, a number of large domestic and foreign communities and interactive Web sites were exposed CSRF vulnerabilities, such as:, Metafilter (a large BLOG site), YouTube and Baidu HI ... and Now, many sites on the Internet is still defenseless, so the security industry called CSRF "sleeping giant".
    Quoted from: /qq_21956483/article/details/78116094

II. CSRF (Web Form Submission)

Setting CSRF tags under web forms can effectively prevent CSRF cross-site attacks (as shown below).

{% csrf_token %}

If you don't set this form, it will be disabled when you visit the web page (as shown below)

To cope with the prohibition of access, in fact, there are many ways, one of which is the configuration file () in the middle of the csrf child removed, so that the original prohibition of access to the page can also be successfully accessed, but the risk of this practice is very large, for security reasons, do not recommend doing so!

Another approach is to add a decorator (@csrf_exempt) in the view layer to achieve local non-detection, in other words, even if you do not add the csrf tag in the web form, as long as you add the decorator, you can successfully access the page, you need to pay attention to is limited to the content of the decorator, the rest of the code does not add the decorator is still forbidden to access the state of the code

CSRF (Web form submission) experiments

Then we'll demonstrate in code what we've said above:

First, configure a subroute under the file under the app

from  import path, re_path
from App import views

urlpatterns = [
    # csrf test
    path('register/',,name = 'register'),
]

Next, write the view function

def register(request):
    if  == "POST": # If the request is a POST request
        username = ('username') # Get the username from the form
        password = ('password') # Get the password from the form
        print(username,password) # Print username, password
    return render(request,'') # Render the template and return it to the content in the web

web form (no csrf tags set)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>enrollment</title>
</head>
<body>
<form ation="" method="post">
    user ID:<input type="text" name="username"><br>
    cryptographic:<input type="text" name="password"><br>
    <input type="submit">
</form>
</body>
</html>

At this point, after turning on the service (python runserver 8090) and accessing the web page, it will show the word forbidden access

So next we set up the csrf tag in the web form

{% csrf_token %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>enrollment</title>
</head>
<body>
<form ation="" method="post">
    {# Preventing cross-site attacks #}
    {% csrf_token %}
    user ID:<input type="text" name="username"><br>
    cryptographic:<input type="text" name="password"><br>
    <input type="submit">
</form>
</body>
</html>

Visit the web page again, and find that the username and password can be submitted normally, and there will be one more csrf implicit pseudo-random number in the form.

CSRF attacks are rooted in the WEB's implicit authentication mechanism! While the WEB's authentication mechanism can guarantee that a request is coming from a particular user's browser, there is no guarantee that the request was approved by the user to be sent!

The idea of CSRF defense mechanism is to add pseudo-random numbers to the client page to achieve a more effective defense against cross-site attacks.

CSRF (ajax submission)

For ajax submission, the following needs to be added to the html

🌈1 referencing jquery

🌈2 Add the prevent cross-site attacks tag

🌈3 Add ajax submit with button

🌈4 Add ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>enrollment</title>
    {# 🌈1 referencing jquery #}
    <script src="/ajax/libs/jquery/1.12.4/"></script>
</head>
<body>
<form ation="" method="post">
    {# 🌈2 Prevent cross-site attacks #}
    {% csrf_token %}
    user ID:<input type="text" name="username"><br>
    cryptographic:<input type="text" name="password"><br>
<!--    {# Form Submission #}-->
<!--    <input type="submit">-->

<!--    {# 🌈3 ajax submit #}-->
    <input type="button" value="Register." >
</form>
</body>
</html>
<script>
	{# 🌈4 ajax #}
    $("#button").click(function(){
        username = $("[name='username']").val();
        password = $("[name='password']").val();
        csrf = $("[type='hidden']").val();
        (username,password,csrf);
        {# $.post("/register/") #}
    });

</script>

There is only one way to pass ajax parameters here, if you want to know more about it, please go todjango the ajax pass parameters of the two formats

After accessing the web page, enter the username, password, and view the review element, the console will display the entered username, password, and an implicit pseudo-random number

Go ahead and add the following to the html

🌈5 post submission

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>enrollment</title>
    {# 🌈1 referencing jquery #}
    <script src="/ajax/libs/jquery/1.12.4/"></script>
</head>
<body>
<form ation="" method="post">
    {# 🌈2 Prevent cross-site attacks #}
    {% csrf_token %}
    user ID:<input type="text" name="username"><br>
    cryptographic:<input type="text" name="password"><br>
<!--    {# Form Submission #}-->
<!--    <input type="submit">-->

<!--    {# 🌈3 ajax submit #}-->
    <input type="button" value="Register." >
</form>
</body>
</html>
<script>
	{# 🌈4 ajax #}
    $("#button").click(function(){
        username = $("[name='username']").val();
        password = $("[name='password']").val();
        csrf = $("[type='hidden']").val();
        (username,password,csrf);

        {# 🌈5 post submit #}
        {# $.post("address",{parameters},function(return value){}) #}
        $.post("/user/register/",{'username':username,'password':password,'csrfmiddlewaretoken':csrf},function(data){
            (data)
        })

    });

</script>

Add the following code to the view layer

🌟 return ajax request

# Local prohibition
# @csrf_exempt
def register(request):
    if  == "POST":
        username = ('username')
        password = ('password')
        print(username,password)

        # 🌟 return ajax request
        return JsonResponse({'code':1})
        # {'code':1} is a custom value

    return render(request,'')

Finally the web page is accessed, the ajax request is successful and the return value {'code':1} is successfully returned

summarize

to this article on Python djanjo csrf anti cross-site attacks on the article is introduced to this, more related to djanjo csrf anti cross-site attacks on the contents of the search for my previous articles or continue to browse the following related articles I hope that you will support me in the future more!