Skip to content

Instantly share code, notes, and snippets.

@lindowx
Last active April 20, 2018 05:20
Show Gist options
  • Save lindowx/1b619379c306a1e4467217ee5de85fc8 to your computer and use it in GitHub Desktop.
Save lindowx/1b619379c306a1e4467217ee5de85fc8 to your computer and use it in GitHub Desktop.
A simple CORS middleware for Lumen framework
<?php
/*
* A simple CORS middleware for Lumen framework
*
* lindowx
*/
namespace App\Http\Middleware;
use Closure;
class SimpleCorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$origin = $request->header('origin');
if (
! empty($origin) &&
preg_match('/^([^:]+):\/\/([^\:]+)(\:\d+)?\/?$/i', $origin, $matches)
) {
//Comma separated string contains multiple origin.
//Supports wildcard pattern
//.env variable examples:
// SIMPLE_CORS_ALLOWED_ORIGINS=example.com
// SIMPLE_CORS_ALLOWED_ORIGINS=*.example.com
// SIMPLE_CORS_ALLOWED_ORIGINS=test.com,*.foor.com
$allowedOriginsCfg = env('SIMPLE_CORS_ALLOWED_ORIGINS');
$allowedOriginsPattern = str_replace(
[' ', ',', '.', '-', '_', '*', ],
['', '|', '\.', '\-', '\_', '.*', ],
$allowedOriginsCfg
);
$pattern = sprintf('/^(%s)$/i', $allowedOriginsPattern);
if ( preg_match($pattern, $matches[2],$m) ) {
return $next($request)
->header('Access-Control-Allow-Origin', $origin)
->header('Access-Control-Allow-Methods', '*')
->header('Vary', 'origin');
}
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment