How protect a RestFul Api in Nodejs?

521 views Asked by At

Nowadays i am using https://github.com/baugarten/node-restful wich helpme to work in an API, the question is?

I am working in Express framework, are there a way to protect the "GET" request from other site to mine.

I use the CSRF from express but only work by POST,PUT,DELETE methods with a message of FOrbidden 403 when treat make anithing since curl in console but if I make a curl toward a Get method curl localhost:3000/posts that giveme an array with all the posts.

  app.use(express.csrf());
  app.use(function(req, res, next){
      res.locals.token = req.session._csrf;
      next();
  });
  app.use(app.router);

What you advice me? are there other modules to work an Api better? How can protect an Api in nodejs? What are the best practices that a haver to learn?

Thanks by your Help.

1

There are 1 answers

1
shawnzhu On

Try Express middleware which is designed to do so. For example:

var express = require('express');
var app = express();

// simple middle ware to protect your URI
app.use(function(req, res, next){
  if (req.method == 'GET') {
     if (!req.locale.token) { res.send(403); } // custom to fit your policy
     else if (req.protocol !== "https") {res.redirect("your-secure-url");}
     else { next(); }
  }
});