I'm looking for the best way to only allow certain domains to access my laravel application. I'm currently using Laravel 5.1 and am using a Middleware to redirect if the referring domain isn't located in the whitelisted domains.
class Whitelist {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//requesting URL
$referer = Request::server('HTTP_REFERER');
//parse url to match base in table
$host = parse_url($referer, PHP_URL_HOST);
$host = str_replace("www.", "", $host);
//Cached query to whitelisted domains - 1400 = 24 hours
$whiteList = Cache::remember('whitelist_domains', 1400, function(){
$query = WhiteListDomains::lists('domain')->all();
return $query;
});
//Check that referring domain is whitelisted or itself?
if(in_array($host, $whiteList)){
return $next($request);
}else{
header('HTTP/1.0 403 Forbidden');
die('You are not allowed to access this file.');
}
}
}
Is there a better way to go about doing this, or am I on the right track?
Any help would be appreciated.
Thanks.
You're on the right track, the implementation seems to be fine.
However, do not trust the HTTP_REFERER as a means of authentication/identification as it can be modified easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With