Home > database >  How to keep my node js endpoints safe and to be accessible only from my website?
How to keep my node js endpoints safe and to be accessible only from my website?

Time:12-31

i have endpoints coded in nodejs... i use following codes to keep them safe...

const corsOption = {
    origin: ['https://www.mywebsite.com'],
};
app.use(cors(corsOption));

if (host !== "myendpoint.com") {
  return res.status(403).json({ message: "forbidden access" });
}

will these keep my endpoints safe... or do i have to do anything more for my endpoints to keep them safe... i dont want bots or anyone else to use it... i know that they are public but i want to restrict access... pls, any help or suggestion ??? thanking you

CodePudding user response:

To be sure you can control who can access your endpoint, you can setup a token authentication. When you send a request to your endpoint, the header should include:

Authorization: Token {your token}

And in your endpoint, you can check if the token is authorized or not (by storing authorized token in a database). If the token is not recognized, you can send back a 403 error.

CodePudding user response:

If your website accesses your endpoints, this means that any browser that can display your website must also be able to access your endpoints. Requests are not made by your website, they are made by browsers visiting your website.

You must first ask how much you want to restrict access:

  • Restrict to individual known users to whom you send a password via mail, which they must then type into your website ("log on") before they can make any requests to your endpoints.
  • Restrict to users who have self-registered. Can anyone in the world then self-register, or do you demand confirmation via an email address?
  • Restrict to users who can log on with their Google (or Facebook, or ...) account.

Zain_Ul_Din's answer shows details of a possible implementation for the "self-registration" case. See also What's the best way to add social login (Sign in with Google) to existing email/password app and database?

CodePudding user response:

Question: will these keep my endpoints safe

Yes it will protect endpoints

but it's not a good practice to hard code host let's suppose you want to allow multiple hosts then this approach will not work.

Instead, you cloud use JWT JSON Web Tokens

Basic Overview

  • Download JWT package
   npm install jsonwebtoken
  • create a secert key
   const jwt = require('jsonwebtoken');
   const secretKey = 'my-secret-key';
   
   const token = jwt.sign({ username }, secretKey);

   // Send the JWT to the client
   res.send({ token });
  • create custom middleware
function verifyToken(req, res, next) {
  // Get the JWT from the request header
  const token = req.headers['x-access-token'];

  // If there is no token, return an unauthorized error
  if (!token) {
    res.sendStatus(401);
  }

  // If there is a token,
  // verify it and attach the decoded payload to the request object
  try {
    const decoded = jwt.verify(token, secretKey);
    req.user = decoded;
    next();
  } catch (err) {
    res.sendStatus(401);
  }
}
  • Use the verify token middleware on protected routes:

app.get('/protected', verifyToken, (req, res) => {
  res.send('Protected route accessed');
});

Learn more about JWT

CodePudding user response:

you can implement user authentication and authorization in your Node js app to restrict access. for this you can use the jsonwebtoken npm package.

Look up John Smilga's node and express projects on google for a 10hr video including 4 projects. One of the projects introduces JSON web tokens and how to use them.I highly recommend that.

You can also use the express-rate-limit package. With this you should be able to 'limit' how many requests a user can make to your API endpoints within a set amount of time. If the requests exceed that limit then this middleware steps in and stops further access (Haven't tested it in production myself but looks good)

  • Related