Chrome警告:
一个站点从网络请求了一个资源,由于其用户的特权网络位置,该站点只能访问该资源。这些请求将设备和服务器暴露在互联网上,增加了跨站点请求伪造(CSRF(攻击和/或信息泄露的风险。为了减轻这些风险,Chrome将要求非公共子资源选择通过飞行前请求访问,并将开始在Chrome 101中屏蔽它们(2022年4月(。若要解决此问题,请确保对专用网络资源的飞行前请求的响应将Access Control Allow private network标头设置为true。
我正在使用烧瓶,但不确定如何将此标题添加到飞行前检查中。我可以手动在响应中添加标题,但如何在飞行前检查中添加标题?
我正在使用Flask Cors,这是代码:
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
我放弃了Flask-Cors
包,并进行了自己的实现:
""" Note:
We need to use functools wraps, or else @route thinks all functions
are named the same, and errors out that a route is overriding another
Test Preflight with:
curl -i -X OPTIONS http://127.0.0.1:5000/foo/
Then test reponse with:
curl -i http://127.0.0.1:5000/api/foo/
"""
from functools import wraps
from flask import Response, request
def add_cors_preflight_headers(response):
allow_request = 'foo' in request.origin
if allow_request:
response.headers['Access-Control-Allow-Origin'] = request.origin
if request.method == 'OPTIONS':
response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
# Allow chrome to access private network ajax requests
response.headers['Access-Control-Allow-Private-Network'] = 'true'
return response
def handle_cors(func):
@wraps(func)
def decorator(*args, **kwargs):
if request.method == 'OPTIONS':
response = Response()
else:
response = func(*args, **kwargs)
response = add_cors_preflight_headers(response)
return response
return decorator
然后使用如下(注意我们如何将选项添加到允许的方法中(:
@app.route("/api/foo/", methods=['GET', 'OPTIONS'])
@handle_cors
def get_foo():
return Response({'foo': 'hello world!'})