Skip to content

Instantly share code, notes, and snippets.

@blood72
Last active January 21, 2021 13:56
Show Gist options
  • Save blood72/e66a6f6840f07516b5cdf7395349adff to your computer and use it in GitHub Desktop.
Save blood72/e66a6f6840f07516b5cdf7395349adff to your computer and use it in GitHub Desktop.
(Laravel) Allow request only if Referrer header is base same domain
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
class RestrictFromReferer
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param int $status
* @return mixed
*/
public function handle($request, Closure $next, int $status = 403)
{
$referer = $request->header('referer', '');
if (! Str::endsWith(base_domain($referer), URL::domain())) {
abort($status);
}
return $next($request);
}
}
@blood72
Copy link
Author

blood72 commented Aug 15, 2020

  • base_domain()
if (! function_exists('base_domain')) {
    /**
     * Get the base host URL from the parameter.
     *
     * @param string $url
     * @return string
     */
    function base_domain(string $url)
    {
        return parse_url($url, PHP_URL_HOST);
    }
}
  • URL::domain()
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

if (! URL::hasMacro('domain')) {
    URL::macro('domain', function (string $sub = '') {
        if ($sub !== '' && ! Str::endsWith($sub, '.')) {
            $sub .= '.';
        }

        return $sub . base_domain(config('app.url'));
    });
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment