我最近将HTTPS添加到了我的网站。我尚未发布产品,但正在使用真实域进行测试,然后重新路由到最终域。在过渡到HTTPS之前,我可以通过视图调用“ SetCitySession”将会话数据设置到服务器,它可以正常运行,并且在我仍在运行的HTTPS之前的环境中仍然可以正常工作。在HTTPS上,它没有运行。我在尝试正确配置它时遇到了各种错误,但是我的持续错误是“ 403-CSRF令牌丢失或不正确”。我不明白为什么。在我的HTTPS之前的环境中,代码可以很好地访问cookie,并且它们存在,通过检查DevTools中的请求标头来验证它们是否存在,但在HTTPS环境中,令牌在那里但未被AJAX检索以用于请求中。我看了看文档,尝试了所有类似@ csrf_protect,@ csrf_exempt等的内容,没有任何变化。在下面的javascript中,由于我正在尝试一切,所以有点a肿,我为Ajax提供了两种方法来检索cookie。我一次只使用一次,但现在都留作参考,所以您会知道我的尝试。两者均失败。更改任何内容后,我都会从浏览器中清除所有缓存和Cookie,因此不会保留任何潜在的持久性。适当的中间件位于settings.py中。我正在运行django 1.11,python 2.7,并使用AWS Elasticbeanstalk,S3进行存储,Route 53进行路由以及仅使用NGIX和Gunicorn的Apache。我究竟做错了什么?下面是正在使用的视图和javascript。
Views.py:
创建错误的设置会话数据视图
def SetCitySession(request):
if request.method == "POST":
request.session['city-name'] = request.POST['cityName']
request.session['city-id'] = request.POST['cityId']
return JsonResponse({})
def GetCitySession(request):
if request.method == "GET":
cityName = request.session['city-name']
cityId = request.session['city-id']
context = {
"cityName": cityName,
"cityId": cityId
}
return JsonResponse(context)
正在呈现事物的主页视图
def IndexPage(request):
if 'city-name' not in request.session:
cityName='Madrid'
request.session['city-name'] = request.POST.get('cityName')
else:
cityName = request.session['city-name']
if 'city-id' not in request.session:
cityId = 1
request.session['city-id'] = request.POST.get('cityId')
else:
cityId = request.session['city-id']
city = get_object_or_404(City, name=cityName)
servercurrency_qs = City.objects.filter(name=cityName).values('currency')
for currency in servercurrency_qs:
if currency['currency'] == 1:
currency_qs = '€'
elif currency['currency'] == 2:
currency_qs = '£'
else:
currency_qs = '$'
venues = ProfileVenue.objects.all().filter()
oc_list = []
for venue in venues:
if Occurrence.objects.filter(date__gte=timezone.now()).filter(event__location=venue).exists() and venue.city.name==cityName:
oc = Occurrence.objects.all().filter(date__gte=timezone.now()).filter(event__location=venue)[:1].get()
oc_list.append(oc)
if len(oc_list) == 3: break
teachers = ProfileTeacher.objects.all().filter().filter(active=True).filter(published=True).filter(city__name=cityName)[:3]
teachers_list = []
for teacher in teachers:
if teacher.city.name==cityName:
teachers_list.append(teacher)
languages = Language.objects.all()
levels = LanguageLevel.objects.all()
events = EventType.objects.all()
context = {
'venues_today': oc_list,
'teachers': teachers,
'languages': languages,
'levels': levels,
'events': events,
'form': form,
'currency_qs':currency_qs,
'servercurrency_qs':servercurrency_qs,
'currency': currency,
'city':city,
}
return render(request, "index.html", context )
javascript :
其中更改城市并设置set-session-data视图的标头javascript:
/* Ciudades */
if(localStorage.getItem("cities") == null){
$.ajax({
url: "/api/cities",
method: "GET",
dataType: "json",
async: false
})
.done(function(data, status){
localStorage.setObject("cities", data);
})
.fail(function(data, status){
});
}
$.each(localStorage.getObject("cities"), function(i, c){
template = '<li><a href="" class="header-city-option" data-id="' + c.id + '" data-name="' + c.name + '">' + c.name + '</a></li>';
$("#header-city-list").append(template);
});
if(localStorage.getItem("city-id") == null){
localStorage.setItem("city-name", $("#header-city-list li:first-child a").data("name") );
localStorage.setItem("city-id", $("#header-city-list li:first-child a").data("id") );
var token = $("input[name*='csrfmiddlewaretoken']")[0].value;
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 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));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: "POST",
url: "set-city-session",
data: {
cityName: city,
cityId: id,
csrfmiddlewaretoken: getCookie('csrftoken'),
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},
},
success: function(){
if(isClicked)
location.reload();
}
});*/
}
else{
localStorage.setItem("city-name", $(localStorage.getItem("city-name"));
localStorage.setItem("city-id", $(localStorage.getItem("city-id"));
}