title: How to verify the origin domain of a request in PHP (Laravel)
body: <p>I am working on a Laravel app where I am building some API for other websites. But I am trying to make the implementation of my API as easy as possible. My expectation is that the user will only use this tag in the HTML head:</p>
  <pre><code>&lt;script src=&quot;api.mydomain.com&quot;&gt;
  </code></pre>
  <p>Now I have a controller on this URL that provides the source javascript with the content-type header, but before it goes there, the router will first execute my authentication middleware. Let's say it looks something like this:</p>
  <pre><code>public static $users = [
      'client1.com',
      'client2.com',
      'client3.com'
  ];
  
  public function handle(Request $request, Closure $next)
  {
      $origin = &quot;HERE I NEED THE ORIGIN URL&quot;; // e.g. client4.com
  
      if ( !in_array($origin, self::$users) ) {
  
          abort(401);
  
      }
  
      return $next($request);
  }
  </code></pre>
  <p>As you can see from the code, I need to retrieve the <strong>$origin</strong> variable. So if a website <em>client1.com</em> will try to insert my <em>javascript</em>, it will successfully get the javascript code. If <em>client4.com</em> tries to access it, it will get a 401 error.</p>
  <p>I found out methods with <strong>$_SERVER['HTTP_REFERER']</strong> or Laravel's <strong>$request-&gt;server('HTTP_REFERER')</strong>, but this data might be spoofed, right?</p>
  <p>In the best-case scenario, I would like to retrieve the original domain and when not available (e.g. from a private cURL request), I would like to get the IP address. And of course, I need it to be secure - clients1/2/3 paid for my API, others didn't.</p>
  <p>How can I do it? Or is there any better method for origin authentication?</p>