0

I am working with Openresty.

Work : I am having a website which is designed in Django and i am retuning response content from directly from nginx by using lua code without going to django if cache is found into redis.

Problem: When i am filling any Form at my page i am getting 403 (csrf_token failure issue). This issue is coming when i am returning data directly from nginx i am not able to generate csrf_tokrn dynamically .

Help Needed: I want to know how can i generate csrf token when i am retuning response directly from redis .

Prashant Gaur
  • 9,540
  • 10
  • 49
  • 71

1 Answers1

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')
    })
fasouto
  • 4,386
  • 3
  • 30
  • 66