我有一个基于Django的D&D-wiki网页,我在空闲时间使用它来学习更多关于web开发的信息。最近,我使用django-csp.实现了一个内容安全策略,由于我只需要处理20个左右的模板,这个切换非常轻松。在这里,我的CSP设置:
//Django settings.py
CSP_DEFAULT_SRC = ("'none'",)
CSP_STYLE_SRC = ("'self'", 'stackpath.bootstrapcdn.com', 'fonts.googleapis.com', "'unsafe-inline'", 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'rawcdn.githack.com', 'maxcdn.bootstrapcdn.com',)
CSP_SCRIPT_SRC = ("'self'", 'localhost', "default-src", 'stackpath.bootstrapcdn.com', 'code.jquery.com', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com','maxcdn.bootstrapcdn.com',)
CSP_IMG_SRC = ("'self'", 'ipw3.org', 'data:', 'cdn.jsdelivr.net', 'cdnjs.cloudflare.com', 'i.imgur.com',)
CSP_FONT_SRC = ("'self'", 'fonts.gstatic.com', 'maxcdn.bootstrapcdn.com',)
CSP_MEDIA_SRC = ("'self'",)
CSP_INCLUDE_NONCE_IN = ('style-src',)最近开始学习AJAX请求,并希望实现一个简单的POST请求。遗憾的是,我的CSP阻止了这个请求,考虑到我允许CSP_SCRIPT_SRC中的self和localhost,我认为应该允许这个请求:
//JS Event Listener that creates and sends the AJAX request
document.getElementById('create-timstamp').addEventListener('click', function(event){
const isValid = validateForm();
if (isValid){
xhr = new XMLHttpRequest();
xhr.open('POST', getCreateTimestampURL(), true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const csrf = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
xhr.setRequestHeader("X-CSRF-TOKEN", csrf);
xhr.onload = function(){
document.querySelector('.timestamp-create-box').remove();
}
const timestampForm = document.forms['timestamp-form'];
const timestamp_seconds = toTimeInt(timestampForm['time'].value);
const timestamp_name = timestampForm['name'].value;
const data = `name=${timestamp_name}&time=${timestamp_seconds}`;
xhr.send(data);
return false;
}
//For completion's sake here also the helper methods used by the event listener
function getCreateTimestampURL(){
return document.querySelector('#add-timestamp').dataset.timestampcreateurl;
}
function toTimeInt(timestampString){
const hours = parseInt(timestampString.substring(0,2));
const minutes = parseInt(timestampString.substring(3,5));
const seconds = parseInt(timestampString.substring(6,8));
return 3600*hours + 60*minutes + seconds;
}在这里浏览器的反应是:
//Webbrowser console output after triggering the event
Content Security Policy: The page’s settings blocked the loading of a resource at http://localhost:8002/files/timestamp/1/17/new (“default-src”).所以我知道我做错了什么,但我不确定是什么。我知道我需要以某种方式调整我的CSP设置,但是我已经允许本地主机脚本,还需要什么?
发布于 2020-09-24 05:33:54
在再读一遍django-csp文档之后,我终于找到了我正在寻找的条目。不知道头几次我是怎么错过的。
您想要更改的条目是CSP_CONNECT_SRC,它自然需要允许("'self'",)发送AJAX请求。
这不是,而不是,这意味着请求的上述代码可以工作。它捕获CSRF令牌的方式是非功能性的,会导致错误。这只是通过CSP的阻塞。
https://stackoverflow.com/questions/64033015
复制相似问题