Hi! I've implemented a simple and naive solution for this problem, but it worked perfectly on my case. Maybe it can help someone else in the future, so I'm sharing it here. If you find any potential problem with this solution, please let me know.
1) Created an extension following this guide https://docs.flarum.org/extend/start.html#architecture
2) Created a Middleware following the instructions clarkwinkelmann referred: https://docs.flarum.org/extend/middleware.html#adding-middleware-in-your-extension . This Middleware verifies for allowed origins and bypass OPTIONS requests if they're coming from the whitelisted origins.
<?php
namespace MyProject\Middleware;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
class HandleCorsMiddleware implements MiddlewareInterface
{
protected function parseOriginUrl($referrerUrl)
{
$referrerUrlStructure = parse_url($referrerUrl);
$origin = $referrerUrlStructure['scheme'] . '://' . $referrerUrlStructure['host'];
if (isset($referrerUrlStructure['port']) && $referrerUrlStructure['port']) {
$origin .= ':' . $referrerUrlStructure['port'];
}
return $origin;
}
protected function setAccessControlHeaders($url)
{
header('Access-Control-Allow-Origin: ' . $url);
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Authorization, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials: true");
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$headers = $request->getHeaders();
$referrer = $headers['referer'] ?? '';
$whitelistedOrigin = false;
if ($referrer) {
$config = app('flarum.config');
$allowedOrigins = $config['allowed_origins'];
$originUrl = $this->parseOriginUrl($referrer[0]);
if (in_array($originUrl, $allowedOrigins)) {
$whitelistedOrigin = true;
$this->setAccessControlHeaders($originUrl);
}
}
if ($whitelistedOrigin && $referrer && $request->getMethod() === 'OPTIONS') {
header('Status: 200');
exit;
}
return $handler->handle($request);
}
}
3) Added my Middleware to extend.php
use Flarum\Extend;
use MyProject\Middleware\HandleCorsMiddleware;
return [
(new Extend\Middleware('api'))->add(HandleCorsMiddleware::class)
];
4) Added the allowed origins to my config.php file
return array(
'debug' => true,
...
'allowed_origins' => [
'http://localhost:3000',
'https://example.com',
'https://staging.example.com',
]
);