Skip to content

Instantly share code, notes, and snippets.

@christoph-daehne
Last active July 4, 2017 06:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christoph-daehne/a3749b115fcddafee7dc51f63a82a7d6 to your computer and use it in GitHub Desktop.
Save christoph-daehne/a3749b115fcddafee7dc51f63a82a7d6 to your computer and use it in GitHub Desktop.
Enable CORS in a Flow Framework Application
<?php
namespace Your\Package\Name\Http;
use Neos\Flow\Http\Component\ComponentChain;
use Neos\Flow\Http\Component\ComponentContext;
use Neos\Flow\Http\Component\ComponentInterface;
/**
* !!! be aware that this component enables CORS for the entire application !!!
*
* add this config to the Settings.yaml of your package
*
* Neos:
* Flow:
* http:
* chain:
* 'preprocess':
* chain:
* 'allowCors':
* component: 'Your\Package\Name\Http\CorsComponent'
* componentOptions:
* origin: '%env:CORS_ORIGIN%'
*
* Sets the CORS headers to allow foreign origins
*/
class CorsComponent implements ComponentInterface
{
/**
* @var array
*/
protected $options;
/**
* @param array $options The component options
*/
public function __construct(array $options = array())
{
$this->options = $options;
}
/**
* @param ComponentContext $componentContext
* @return void
*/
public function handle(ComponentContext $componentContext)
{
$origin = $this->options['origin'] ?: '*';
$request = $componentContext->getHttpRequest();
$response = $componentContext->getHttpResponse();
$response->setHeader('Access-Control-Allow-Origin', $origin);
$response->setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS');
$response->setHeader('Access-Control-Allow-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
if ($request->getMethod() === 'OPTIONS') {
$response->setHeader('Access-Control-Max-Age', '1728000');
$response->setStatus(204 /* no content */);
$componentContext->setParameter(ComponentChain::class, 'cancel', true);
} else {
$response->setHeader('Access-Control-Expose-Headers', 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
}
}
}
@christoph-daehne
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment