同源资源共享 (CORS) 是一项在网络浏览器中实施的安全功能,其允许或限制网页向与提供网页的域名不同的域名发出请求。
它是一种机制,允许受控地访问给定域名外部的资源。
CORS 对于启用不同 Web 应用程序之间的安全通信至关重要,同时防止恶意跨源请求。
通过指定特定标头,服务器可以指示允许哪些源访问其资源,从而在可用性和安全性之间取得平衡。
实现 CORS 支持的良好流程图:CORS Server Flowchart
你可以在这里阅读规范:https://fetch.spec.whatwg.org/#cors-protocol
对于简单的 CORS 请求,服务器只需要将以下标题添加到其响应中即可
Access-Control-Allow-Origin: <domain>, ...
以下代码应该启用延迟 CORS。
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($request, $handler) {
$response = $handler->handle($request);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});
可选:将以下路由添加为最后一个路由
use Slim\Exception\HttpNotFoundException;
/**
* Catch-all route to serve a 404 Not Found page if none of the routes match
* NOTE: make sure this route is defined last
*/
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function ($request, $response) {
throw new HttpNotFoundException($request);
});
这是一个完整的 CORS 示例应用程序,它使用了 CORS 中间件
<?php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Slim\Factory\AppFactory;
require_once __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
// Add the RoutingMiddleware before the CORS middleware
// to ensure routing is performed later
$app->addRoutingMiddleware();
// Add the ErrorMiddleware before the CORS middleware
// to ensure error responses contain all CORS headers.
$app->addErrorMiddleware(true, true, true);
// This CORS middleware will append the response header
// Access-Control-Allow-Methods with all allowed methods
$app->add(function (ServerRequestInterface $request, RequestHandlerInterface $handler) use ($app): ResponseInterface {
if ($request->getMethod() === 'OPTIONS') {
$response = $app->getResponseFactory()->createResponse();
} else {
$response = $handler->handle($request);
}
$response = $response
->withHeader('Access-Control-Allow-Credentials', 'true')
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', '*')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
->withHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->withHeader('Pragma', 'no-cache');
if (ob_get_contents()) {
ob_clean();
}
return $response;
});
// Define app routes
$app->get('/', function (ServerRequestInterface $request, ResponseInterface $response) {
$response->getBody()->write('Hello, World!');
return $response;
});
// ...
$app->run();
如果请求包含凭据(Cookie、授权头或 TLS 客户端证书),你可能需要在响应对象中添加一个 Access-Control-Allow-Credentials
头。
$response = $response->withHeader('Access-Control-Allow-Credentials', 'true');