Reputation: 141
I have my REST Base APi on Slim Framework. I will need a help in restricting some URL which should only be accessible internally and not exposed public. How can i achieve this please.
/REST/api/v1/getusers -- is publicly available
/REST/api/v1/userinfo -- new api which i want only local access i.e other systems on the network can access but not exposed publicly
Upvotes: 1
Views: 2459
Reputation: 8738
I've created a middleware for this: its name is Slim-Restrict-Route and you can find it here. It uses the Ip
Validator of Respect/Validation and rka-ip-address-middleware.
You can register it in this way:
$app->add(new RKA\Middleware\IpAddress());
$options = array(
'ip' => '192.*.*.*'
);
$app->get('/api/myEndPoint',function ($req, $res, $args) {
//Your amazing route code
})->add(new \DavidePastore\Slim\RestrictRoute\RestrictRoute($options));
Upvotes: 1
Reputation: 12778
Firstly add rka-ip-address-middleware
to determine the client's IP address. You can install this using composer require akrabat/rka-ip-address-middleware
:
$app->add(new RKA\Middleware\IpAddress());
Now, create a group and put all restricted routes inside it. You can then add middleware to the group to ensure that the client IP address is allowed before any of the routes in the group are run:
$app->group('', function () {
$app->get('/REST/api/v1/userinfo', UserInfoAction::class);
// other $app->get(), $app->post(), $app->put() etc actions here
})->add(function ($request, $response, $next) {
// Only allow internal IP addresses
$allowed = ['127.0.0.1', '192.168.0.1']; // or whatever
$clientIp = $request->getAttribute('ip_address');
// Is the client's IP address in the allowed list?
if (!in_array($clientIp, $allowed)) {
// Not allowed: return a 401 error
return $response->withStatus(401);
}
// Allowed: continue to action
return $next($request, $response);
});
Upvotes: 2