我从python-flask
和angular
开始,我使用this snippet来处理csrf。使用ajax调用它总是给我403错误。我没有得到,我在这里做错了什么。
我已经完成了许多答案并尝试了google search中的所有选项。但没有运气。我没有到达我犯错的地方。
烧瓶代码:
@app.route('/targetapi/', methods=['POST'])
def fetch_targets():
""" """
data_dict = {}
acc_ids = request.args['acc_ids']
data_dict['username'] = session.get('username')
data_dict['targets'] = some_func(acc_ids)
return jsonify(data_dict)
角度代码: HTML页面:
<input name="_csrf_token" type=hidden ng-model="csrf_token" ng-init="csrf_token='{{ csrf_token() }}'" >
Ajax电话:
$http({
method : "POST",
url : '/targetapi/',
headers : { xsrfHeaderName: 'X-CSRFToken', xsrfCookieName : csrf_token },
data : { acc_ids : accountIDs }
})
我不知道为什么我会收到403 Forbidden回复:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>403 Forbidden</title>
<h1>Forbidden</h1>
<p>You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.</p>
*来自Chrome-Developer Tool的回复
答案 0 :(得分:1)
检查Chrome是否在发布请求之前发送选项请求。如果是这样,您可以尝试类似:
from flask import current_app
@app.route('/targetapi/', methods=['POST', 'OPTIONS'])
def fetch_targets():
if request.method=='OPTIONS':
response = current_app.make_default_options_response()
else:
data_dict = {}
acc_ids = request.args['acc_ids']
data_dict['username'] = session.get('username')
data_dict['targets'] = some_func(acc_ids)
return jsonify(data_dict)