Skip to content

Instantly share code, notes, and snippets.

@shov
Last active February 8, 2024 18:29
Show Gist options
  • Save shov/080da49891fb5544fe058cd10fcb3730 to your computer and use it in GitHub Desktop.
Save shov/080da49891fb5544fe058cd10fcb3730 to your computer and use it in GitHub Desktop.
Laravel middleware to Allow Cross Origin CORS
<?php
namespace App\Http\Middleware;
use Closure;
use Symfony\Component\HttpFoundation\Response;
/**
* The after middleware to allow specific Access-Control-Allow-Origin
*/
class AllowCrossOrigin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
/** @var Response $response */
$response = $next($request);
$allowedOrigins = explode(';', env('ALLOWED_ORIGINS', ''));
if (in_array('*', $allowedOrigins)) {
$response->headers->set('Access-Control-Allow-Origin', '*');
} else {
$origin = $request->headers->get('Origin');
$noPortOrigin = preg_replace('/^(https?)(\:\/\/)([^\:]{1,})(\:[0-9]{0,})?$/', '$1$2$3', $origin);
foreach ($allowedOrigins as $allowedOne) {
if ($noPortOrigin === $allowedOne)
$response->headers->set('Access-Control-Allow-Origin', $origin);
}
}
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, HEAD, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment