跳转至

Insecure Cross-Origin Resource Sharing (CORS) policy

不安全的跨域资源共享(CORS)策略

描述

跨域资源共享(CORS)使用 HTTP 标头让 Web 客户端能够访问不同域上服务器的资源。出于安全目的,浏览器限制从脚本内发起的跨域 HTTP 请求。

如果策略允许另一个域,那么该域就可以攻击应用程序的用户。如果用户登录到应用程序,并访问策略允许的域,那么在该域上运行的任何恶意内容都可以从应用程序检索内容,并在登录用户的安全上下文中执行操作。

建议

为了降低与跨域资源共享(CORS)相关的安全风险,您可以实施服务器端控制,以根据请求客户端的源限制对资源的访问。

const express = require('express');
const cors = require('cors');
const app = express();

// Define a whitelist of allowed origins
const whitelist = ['http://example1.com', 'http://example2.com'];

// Configure CORS options
const corsOptions = {
  origin: function (origin, callback) {
    if (whitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true); // Allow request
    } else {
      callback(new Error('Not allowed by CORS')); // Deny request
    }
  }
};

// Apply CORS middleware with configured options
app.use(cors(corsOptions));

// Define routes
app.get('/', (req, res) => {
  res.send('Hello World!');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)

# 定义允许的来源列表
allowed_origins = [
    'http://example.com',
    'https://example.com',
    # 根据需要添加更多来源
]  

# 使用白名单初始化 CORS
CORS(app, origins=allowed_origins) 

# 定义路由
@app.route('/')
def hello_world():
    return jsonify(message='Hello World!')

if __name__ == '__main__':
    app.run(debug=True)
<?php

// Enable CORS
header('Access-Control-Allow-Origin: http://example.com');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');

// Handle CORS pre-flight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Methods: GET, POST');
    header('Access-Control-Allow-Headers: Content-Type');
    exit;
}

// Define your API logic
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo json_encode(array('message' => 'Hello World!'));
} else {
    http_response_code(405); // Method Not Allowed
}
?>

链接

标准

  • PCI_STANDARDS:
    • REQ_2_2
    • REQ_6_2
    • REQ_6_3
    • REQ_7_3
    • REQ_8_3
    • REQ_11_3
  • HIPAA_CONTROLS:
    • SECURITY221
    • SECURITY212
    • SECURITY213