eko3alpha / slim-cors-middleware
Slim 3 CORS Multi-Origin Middleware
Installs: 39 122
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 0
Forks: 2
Open Issues: 1
Requires
- php: >=5.5.0
- psr/http-message: ^1.0
Requires (Dev)
- phpunit/phpunit: 5.6
- slim/slim: ~3.0
This package is not auto-updated.
Last update: 2024-12-22 03:26:00 UTC
README
A middleware to handle Cors for multiple domains using Slim. "Access-Contro-Allow-Origin" only accepts one domain or a wildcard. This makes it troublesome if you want to allow different domains access to your api. In order to allow access to multiple domains You either need to create an .htaccess/apache rule: credit
<FilesMatch "\.(ttf|otf|eot|woff|js|css|woff2)$">
<IfModule mod_headers.c>
SetEnvIf Origin "^http(s)?:\/\/(www\.|dev\.|local\.)?(domain\.com|domain2\.com)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
</FilesMatch>
Or you have to use a wildcard. It's an all or very restrictive approach, which encourage most dev's to opt for the very easy wildcard '*' approach.
Access-Control-Allow-Origin: *
This middleware will detect the origin of a request, if its within the allowed list it will set the proper "Access-Control-Allow-Origin" value for that domain, as well as restrict the methods it has access to.
Access-Control-Allow-Origin: https://client.domain.com
Install
You can either download manually or use composer.
composer require eko3alpha/slim-cors-middleware
Usage
$app = new \Slim\App(); $app->add(new \Eko3alpha\Slim\Middleware\CorsMiddleware([ 'https://dev.domain1.com' => ['GET', 'POST'], 'https://dev.domain2.com' => ['GET', 'POST'], 'https://dev.domain3.com' => ['GET'] ]);
Examples
This middleware allows you to add method restrictions on a per domain basis. Below are some examples of valid configuration options. HTTP and HTTPS are considered 2 different origins.
One entry with a wildcard, this will give GET access to all domains requesting resources
$app->add(new \Eko3alpha\Slim\Middleware\CorsMiddleware([ '*' => 'GET' ]);
This will give GET, POST and DELETE access to both http and https versions of api.domain.com, you can either use a string value or array.
$app->add(new \Eko3alpha\Slim\Middleware\CorsMiddleware([ 'http://client.domain.com' => 'GET, POST, DELETE', 'https://client.domain.com' => ['GET', 'POST', 'DELETE'] ]);
You can either choose to have your methods as an array ['GET', 'POST'] or string 'GET, POST'.
Slim Container
You can use Slim's container to hold the configuration if you prefer to have your configuration in a seperate file.
$container = new Slim\Container; . . . $container['cors'] = ['*' => 'GET, POST']; . . . $app->add(new \Eko3alpha\Slim\Middleware\CorsMiddleware($container['cors']);