How to secure Slim Rest API by allowing only certain domain?

I would to allow only certain domains which can access the rest api.
Is it possible?

Yes. Write a middleware.

No idea sir. I will try google to write a middleware for securing RestAPI.
Is there any technical term for this?
Is CROS used for this?

Hi!

I will try google to write a middleware for securing RestAPI.
Is there any technical term for this?

REST is not a “real standard” it’s more a “architectural style”. There are a lot of good/best practices available online about REST / RESTful API’s:

Is CROS used for this?

I think you mean CORS, right?

Cross-Origin Resource Sharing (CORS) is a technique for relaxing the same-origin policy, allowing Javascript on a web page to consume a REST API served from a different origin.

More infos an how to enable CORS in Slim:
https://www.slimframework.com/docs/cookbook/enable-cors.html

1 Like

Hello @mahesh,

Below is an example using middleware:

$app = new \Slim\App();

// adding middleware to all requests to check the domain of the client
$app->add(function ($req, $res, $next) {
    if ($_SERVER['REMOTE_ADDR'] !== 'example.com') {
        // domain not allowed, return 403 Forbidden response
        return (new Slim\Http\Response())
		        ->withStatus(403)
		        ->withJson(['error' => 'access denied']);
    }

    return $next($req, $res);
});

$app->get('/', function ($req, $res) {
  return $res->withJson(['message' => 'success']);
});

$app->run();

If you are looking for existing middleware, you may want to look at https://github.com/oscarotero/psr7-middlewares#firewall

Note that you can also restrict access by configuring your web server, for example with access control in Apache.

2 Likes