I want to allow some routes to only respond to requests made by my front-end website, meaning block other sources like postman and allow only the request from domain of the front-end for security reasons.
Is it possible?
for example, I have a webpage to check the dynamic value of the link and verify if the token on link is on database or not, I can think of putting captcha so a bot can't check all possible combinations, but it's not 100% safe.
if your main problem is bots getting all combinations, the throttling middleware alongside using captchas will help you with that.
By default, all your API routes (in routes/api.php
) allow for a maximum of 60 requests per minute per IP. You can modify this amount to your own need in app/Http/Kernel.php
file by changing the throttle:api
section:
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
changing it to throttle:30:1
for example will mean you will allow 30 requests per minute per ip.
if you only want some routes on your api to be throttled, you can use the middleware elsewhere:
Route::get('my-method', MyController::class)->middleware('throttle:30:1');
if you want to limit exactly by domain, what you are looking for is probably a custom middleware. Middlewares allow you to inspect various request properties (including the request's host through $request->getHost()
) and prevent any controllers or methods.
Although Laravel's default TrustHosts
middleware provides a global host validation, you could create your own custom middleware for specific paths that would look like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class LocalOnly
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
if($request->getHost() != 'localhost')
{
return response('', 400);
}
return $next($request);
}
}
Note: if you are creating new middlewares, you will need to register them. Laravel has its own guide on this here.
in this example, when used on any route, Laravel will reject any host other than localhost
(so even 127.0.0.1
will be rejected)
Personally, I don't recommend doing this as the built-in throttling is a much more elegant solution but in case you really need to do it, here you go.