SoFunction
Updated on 2024-10-29

Django csrf checksum implementation

Introducing:

Usually, the essence of a phishing website is to essentially build a page that looks exactly like a normal website, where the user completes the transfer function

The transfer request is indeed submitted towards the server side of the normal website, the only difference is that the recipient account holder is different.

If you want to simulate a phishing site, you can write a form for the user The input box of the other account does not have a name attribute, and then you quietly write an input box with a default and hidden name attribute in advance.

To solve this problem, when a transfer request is sent to the server, the server returns a randomized real-time string to each machine. Next time, if there is a request sent to the server, the server will check the string, and if it doesn't match, the server will deny access. This is the csrf checksum.

So how does a form form do csrf checksums?

All you need to do is write a {% csrf_token %} inside your form form and you're done!

Three ways to set csrf_token for Ajax requests

Example:

urlpatterns = [
    url(r'^transfer/', ),
]

STATIC_URL = '/static/'
STATICFILES_DIRS = [(BASE_DIR,'static')]

The third way of js file (the official document to apply on the line)

function getCookie(name) {
    var cookieValue = null;
    if ( &&  !== '') {
        var cookies = (';');
        for (var i = 0; i < ; i++) {
            var cookie = (cookies[i]);
            // Does this cookie string begin with the name we want?
            if ((0,  + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(( + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

def transfer(request):
    if  =='POST':
        username = ('username')
        target_user = ('target_user')
        money = ('money')
        print('%s to %s transfer %s dollars' %(username,target_user,money))
    return render(request,'')

front end page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/jquery/3.4.1/"></script>
    <link href="/twitter-bootstrap/3.4.1/css/" rel="external nofollow"  rel="stylesheet">
    <script src="/twitter-bootstrap/3.4.1/js/"></script>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}
    <p>username:<input type="text" name="username"></p>
    <p>target_user:<input type="text" name="target_user"></p>
    <p>money:<input type="text" name="money"></p>
    <input type="submit">
</form>
<button >dispatchajaxrequesting</button>


{% load static %}
<script src="{% static '' %}"></script>
<script>
    $('#d1').click(function () {
        $.ajax({
            url:'',
            type:'post',
            // The first way is to get it yourself manually.
            {#data:{'username':'jason','csrfmiddlewaretoken':$('input[name="csrfmiddlewaretoken"]').val()},#}
            // The second way utilizes template syntax
            {#data:{'username':'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},#}
            // The third generic way of introducing external js files.
            data:{'username':'hank'},
            success:function (data) {
                alert(data)
            }
        })
    })
</script>
</body>
</html>

csrf decorator

The csrf decorator acts on the FBV

Decorator module import:

from  import csrf_exempt,csrf_protect

While our site as a whole checks for csrf, I'd like to leave a few view functions unchecked.

@csrf_exempt # Add to whichever view function does not check csrf for that view

While our site as a whole doesn't check csrf, I'd like to have a couple of view functions that do.

@csrf_protect  #Add to which view function the,Checksums are given to whichever viewcsrf

Note: You need to log out of '' at the same time as validation.

The csrf decorator acts on the CBV

While our site as a whole doesn't check csrf, I'd like to have a couple of view functions that do.

from  import View
from  import method_decorator
from  import csrf_exempt,csrf_protect


# @method_decorator(csrf_protect,name='post') #The second one names a given method and loads it with the
class MyHome(View):
    @method_decorator(csrf_protect)  #The third one # #Load all the methods in the class with #
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request,*args,**kwargs)

    def get(self,request):
        return HttpResponse('get')
    # @method_decorator(csrf_protect) #firstway
    def post(self,request):
        return HttpResponse('post')

Note: You need to log out of '' at the same time as validation.

While our site as a whole checks for csrf, I'd like to leave a few view functions unchecked.

Summary: Adding decorators to CBV Recommended module method_decorator

csrf_exempt can only be loaded for dispatch methods.

to this article on the realization of the Django csrf checksum article is introduced to this , more related Django csrf checksum content please search my previous posts or continue to browse the following related articles I hope that you will support me in the future more !