[Answer]-Generate csrf_token in nginx by using Openresty with Django as a backend server

1👍

I didn’t try it but this nginx conf file could be helpful https://github.com/shrikeh/csrf-nginx-redis-lua

Another option is to leave the token out of the template and get it dinamically from Django via ajax as suggested here. Shameless copy and paste:

// JS code
$.ajax({
    url: // your csrf url,
    type: 'GET',
    data: {type: 'login'},  // only if you need a session id for cookie login
    dataType: 'json',
    success: function(data) {
        $('form').each(function() {
            $(this).append(
                '<input type=hidden name=csrfmiddlewaretoken ' +
                    ' value="' + data.token + '">');
        });
    }
});

// Django code
# views.py, don't forget to add to urls.py
def get_csrf(request):
    if request.GET.get('type') == 'login':
        request.session.set_test_cookie()
    return JSONResponse({
        'status': 1,
        'token': getattr(request, 'csrf_token', 'NOTPROVIDED')
    })

Leave a comment