简体   繁体   中英

CSRF protection to a view with a download api request

I have this view in my application that calls an api to download a pdf:

@login_required
def generateContractPdf(request):
   file_id = request.POST.get('contract')  
   contract_id = request.POST.get('contract')    
   payload = {"file_id": file_id}
   data = {"data": json.dumps(payload, default=str)}
   headers = {'content-type': 'application/json'}
   brokkr = os.environ.get("BROKKR_ADDRESS", default='localhost')
   response = requests.post('http://'+brokkr+':5000/contract', params=data, headers=headers)

   filename=str(contract_id)+".pdf"
   response = HttpResponse(response.content, content_type='application/pdf')
   response['Content-Disposition'] = 'attachment; filename="'+filename+'"'

   return response

But I just realiced that if I dont use render() the csrf doens't work, so this view could be exploited.

How can i transforme it to keep that protection?

You can apply csrf_protect decorator onto your view for the protection of CsrfViewMiddleware to a view.

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def generateContractPdf(request):
    --- Your logic ---

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM