在Restler 3 API上启用CORS的正确方法

时间:2013-10-15 17:53:14

标签: cors restler

Restler3真是不可思议!

我们有一个“公共”API,一个基于API_KEY的访问控制的“管理”API,我们希望另一个受CORS保护的API(无API_KEY)。

新的受CORS保护的API将用于保护我们所有的javascript ajax调用。我们希望将所有ajax服务器端代码集中到一个具有一致入口和出口点的API中。

我们设置了以下Restler默认值。

Defaults::$crossOriginResourceSharing = true;
Defaults::$accessControlAllowOrigin = 'https://www.mydomain.com';

这是正确的技术吗?

我们如何确认安全性是否正常?

作为参考,这是我们为这个新API创建的index.php。

// get the document root from apache and make sure that there is a trailing slash
$document_root = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/';

// autoload Restler
// note: this code was provided by Arul to address issues with autoloading Swift and Aws
$loader = require_once $document_root . 'vendor/autoload.php';
$loader->setUseIncludePath(true);
class_alias('Luracast\\Restler\\Restler', 'Restler');

// import namespaces
use Luracast\Restler\Defaults;
use Luracast\Restler\Restler;

// setup versioning
Defaults::$useUrlBasedVersioning = true;

// setup CORS on this API
Defaults::$crossOriginResourceSharing = true;
Defaults::$accessControlAllowOrigin = 'https://www.mydomain.com';

// instantiate restler
$r = new Restler();

// support both Json and Xml formats
$r->setSupportedFormats('JsonFormat', 'XmlFormat');

// api version
$r->setAPIVersion(1);

// create resources.json at API Root for use by API Explorer
$r->addAPIClass('Luracast\\Restler\\Resources');

// autoload the Diagnostics class in the v1 folder
$r->addAPIClass('Diagnostics');

// start
$r->handle();

响应标题。

Date: Tue, 15 Oct 2013 17:50:12 GMT
X-Powered-By: PHP/5.3.27
Connection: Keep-Alive
Content-Length: 50
Server: Apache
Content-Type: text/html
Keep-Alive: timeout=5, max=94

1 个答案:

答案 0 :(得分:1)

是的,你正在为CORS做正确的

为了测试它尝试通过javascript调用api方法。如果它适用于未启用的域,则表明其无法正常工作

同样,如果它对启用的域不起作用,那也是错误的