CORS Policy Tester
测试和调试CORS配置,包含模拟浏览器场景。
用逗号分隔多个源。使用 * 允许任何源(但不能与凭证一起使用)
关于此工具
跨源资源共享(CORS)是一种关键的网络安全机制,用于控制浏览器如何处理不同域之间的请求。CORS策略配置错误会导致应用程序无声地失败,而过度宽松的策略会使API暴露于不必要的访问风险。CORS Policy Tester通过模拟真实的浏览器场景,帮助开发者在不需要设置多个域或部署测试代码的情况下理解和验证服务器的CORS配置。
使用此工具时,输入您的API端点URL,并选择与您的用例相匹配的场景,例如同源请求、带有简单头的跨源请求,或包含自定义头或HTTP方法的复杂预检请求。该工具将模拟浏览器的CORS验证过程,并精确显示您的服务器应在响应中发送的头部内容、请求是否会成功,以及当策略配置不当时浏览器会显示的错误信息。这样您可以在投入生产环境之前轻松调试CORS问题。
此工具对于处理REST API、微服务或任何需要来自不同域的网页客户端请求的后端开发者来说是无价的。当在前端和后端运行在不同端口的本地环境中开发,或集成第三方服务时,它特别有用。通过测试各种CORS场景,您可以确保API既安全又功能完整。
常见问题
代码实现
# CORS headers generator (Flask example)
from flask import Flask, request, jsonify
app = Flask(__name__)
CORS_CONFIG = {
"allowed_origins": ["https://example.com", "https://app.example.com"],
"allowed_methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allowed_headers": ["Content-Type", "Authorization", "X-Requested-With"],
"allow_credentials": True,
"max_age": 86400,
}
def add_cors_headers(response, origin):
allowed = CORS_CONFIG["allowed_origins"]
if origin in allowed or "*" in allowed:
response.headers["Access-Control-Allow-Origin"] = origin
if CORS_CONFIG["allow_credentials"]:
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = ", ".join(CORS_CONFIG["allowed_methods"])
response.headers["Access-Control-Allow-Headers"] = ", ".join(CORS_CONFIG["allowed_headers"])
response.headers["Access-Control-Max-Age"] = str(CORS_CONFIG["max_age"])
return response
@app.before_request
def handle_preflight():
if request.method == "OPTIONS":
response = app.make_default_options_response()
return add_cors_headers(response, request.headers.get("Origin", ""))
@app.after_request
def apply_cors(response):
origin = request.headers.get("Origin", "")
return add_cors_headers(response, origin)
@app.route("/api/data")
def data():
return jsonify({"message": "CORS configured successfully"})Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.