I would like to have a dynamic CORS with Nelmio to allow people using my API, and protect from unsafe user.
Ex: in my database I have a list of ORIGIN that’s allowed to use it with an X-API-KEY
------------------------------------------
| id | origin | api_key |
------------------------------------------
| 1 | http://test.com | abcdefgh |
------------------------------------------
In the .env I put allowed on every request
NELMIO_CORS = "*"
But I added a MiddleWare subscribed to request event on the Kernel, and send to CORS function a list of origin’s allowed
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::EXCEPTION => 'onKernelException',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
private function CORS($request, array $allowedOrigins = ['*'])
{
if ($request->getMethod() === 'OPTIONS') {
if (in_array($request->headers->get('Origin'), $allowedOrigins)) {
$key = array_search($request->headers->get('Origin'), $allowedOrigins);
$request->headers->set('Access-Control-Allow-Origin', $allowedOrigins[$key]);
} else {
$request->headers->set('Access-Control-Allow-Origin', 'http://fake.net');
}
$request->headers->set('Access-Control-Allow-Headers', 'X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization');
$request->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
$request->headers->set('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
$request->headers->set('Content-Type', 'application/json');
}
}
The problems are:
- If user can fake the request, and dont send OPTIONS method so he can bypass, right ?
- What is the best way to do ?