Reputation: 4783
I wanted to set up a dynamic CORS middleware which would check on the fly if the subdomain I am using is the valid subdomain for my server. I have tested the logic behind it and it works, but when providing a variable to the header, it seems as if something isn't right?
Here is the code:
public function handle($request, Closure $next)
{
$originalDomain = config('session.domain');
$parsedUrl = parse_url(request()->url());
$splitDomain = explode('.', $parsedUrl['host'], 2);
$subdomain = $splitDomain[0];
$domain = $splitDomain[1];
$subdomainValid = $parsedUrl['host'] != $originalDomain && $originalDomain == $domain;
if(!$subdomainValid)
return $next($request);
$allowedUrl = $parsedUrl['scheme'] . '://' . $subdomain . '.' . config('session.domain_without_dot');
return $next($request)
->header('Access-Control-Allow-Origin', $allowedUrl)
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
I am getting the error that No 'Access-Control-Allow-Origin' header is present on the requested resource
, but if I dump the variable I got, and paste it in, it works just fine.
Upvotes: 2
Views: 539
Reputation: 4783
I have resolved the issue by changing
$parsedUrl = parse_url(request()->url());
to
$parsedUrl = parse_url($_SERVER['HTTP_ORIGIN']);
Explanation
Since this middleware is put on the server, when request goes through the middleware, the request()->url()
is actually the value of the server URL, not of the subdomain requesting it. With this change I am fetching an URL of the subdomain which requested the server resource.
Upvotes: 1