Last active
July 4, 2017 06:31
-
-
Save christoph-daehne/a3749b115fcddafee7dc51f63a82a7d6 to your computer and use it in GitHub Desktop.
Enable CORS in a Flow Framework Application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For more information, see https://sandstorm.de/de/blog/post/enable-cors-in-the-flow-framework.html