CORS policy setup in Dotkernel using mezzio-cors
Access to fetch at RESOURCE_URL from origin ORIGIN_URL has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Most developers have encountered this error when interacting with APIs. In this article we will run through the steps required to fix it.
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources.
The library we are going to use is Mezzio CORS .
Install package Mezzio CORS
Run the following command in your application’s root directory:
composer require mezzio/mezzio-cors
Open your application’s config/config.php file and add the following lines to the
Open your application’s config/pipeline.php file and add the following line (preferrably between ErrorHandlerInterface::class and the handler/middleware that will return your response):
Don’t forget to add the corresponding use at the top of the file:
Create config file
Create and open file config/autoload/cors.local.php and add the following code inside it:
<?php declare(strict_types=1); use Mezzio\Cors\Configuration\ConfigurationInterface; return [ ConfigurationInterface::CONFIGURATION_IDENTIFIER => [ 'allowed_origins' => [ ConfigurationInterface::ANY_ORIGIN ], 'allowed_headers' => ['Accept', 'Content-Type', 'Authorization'], 'allowed_max_age' => '600', 'credentials_allowed' => true, 'exposed_headers' => , ], ];
Note the value
ConfigurationInterface::ANY_ORIGIN stored under
allowed_origins. Leaving this value as is, makes your application accessible by any origin (permissive mode). To restrict access, replace it with a list of origins that should have access to your application (restrictive mode), for example:
'allowed_origins' => [ "domain1.com", "domain2.com" ],
Don’t forget to make a distributable version of you config/autoload/cors.local.php and add that to your repository.
Make sure your application sends the Origin header and it is set to the correct value, for example example.com.
In your config/autoload/cors.local.php:
- when in permissive mode, you should see the expected response from the resource
- when in restrictive mode, if the request origin is not listed under
allowed_origins, you should see a 403 Not authorized response