1

I am calling a login method from subdomain on main domain, and I made a CORS middleware which should take care of it. However it doesn't work as expected.

I want to check if requests came from a specific domain, so I tried doing this:

public function handle($request, Closure $next)
{
    if(!isset($_SERVER['HTTP_REFERER']))
        return $next($request);

    $originalDomain = config('session.domain');

    $parsedUrl = parse_url($_SERVER['HTTP_REFERER']);
    $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');

    return $next($request)
        ->header('Access-Control-Allow-Origin', $allowedUrl)
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Origin, x-requested-with, x-csrf-token');
}

But the issue I'm having is that $_SERVER['HTTP_REFERER'] sometimes doesn't return the value I expect. Shouldn't it return origin of the request?

Norgul
  • 4,613
  • 13
  • 61
  • 144
  • **'HTTP_REFERER' The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.** – madalinivascu Dec 12 '17 at 07:44
  • Okay, and the solution? – Norgul Dec 12 '17 at 07:46
  • use a static url? – madalinivascu Dec 12 '17 at 07:48
  • I have 3500 subdomains, from each you can call a login method. How do you propose having a static url :) – Norgul Dec 12 '17 at 08:04
  • 1
    then you need something like https://stackoverflow.com/a/27990162/1906356 – madalinivascu Dec 12 '17 at 08:09
  • This works more or less the same way as the regex there (I saw that post before), the issue is getting the right referer so that parsing can take place – Norgul Dec 12 '17 at 08:30

1 Answers1

0

I actually changed referrer to origin and added this part of code which resolves my issue:

    if (isset($_SERVER['HTTP_ORIGIN']))
        $referrer = $_SERVER['HTTP_ORIGIN'];
    else
        $referrer = request()->url();
Norgul
  • 4,613
  • 13
  • 61
  • 144