Timir Baran Kundu
Timir Baran Kundu

Reputation: 31

How to secure a simple GET request using Express js

I have build a simple web server using Express js. There I have one GET request to send any json response. Now this request can be accessed from anywhere by anyone.

How can I restrict this GET request from having public access and what approach should I follow to restrict this public access?

Please note, I don't have the login or logout feature, only simple GET request.

Below is my code ---

const express = require('express');
const app = express();
app.get('/', (req, res) => { res.send('Test response'); });
app.listen(3000, () => console.log('Listening on port 3000!'));

Upvotes: 1

Views: 569

Answers (1)

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

There are multiple ways to secure a route. One way can be IP whitelisting.

So basically, you can give particular IPs access to the route. For that you can use express-ipfilter

// Init dependencies
const express = require('express')
const ipfilter = require('express-ipfilter').IpFilter

// Whitelist the following IPs
const ips = ['127.0.0.1']//add the IPs here

// Create the server
app.use(ipfilter(ips, { mode: 'allow' }))
app.get('/', (req, res) => { res.send('Test response'); });
app.listen(3000, () => console.log('Listening on port 3000!'));

There are countless ways to give access to certain person your route:

  1. Private key encryption, sharing a secret key with someone you want access. Whenever your route is called you check the secret key
  2. Public key, You can share your certificate with them, they need to pin the certificate in their request module and hit the route etc.

Upvotes: 1

Related Questions