简体   繁体   中英

How to protect API endpoint?

Beginner in Node.js/Express, I want my front end to fetch some data from an endpoint ( '/1' ) but I don't want a user to see the JSON data when they visit that endpoint. Any help would be appreciated.

app.js

var express = require('express');
var app = express();
var PORT = process.env.PORT || 3000;
app.use("/static", express.static('./static/'));

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/index.html')
});

app.use('/1', function(req, res, next) {
  res.status(404).send('Data not available to end user');
})

app.get('/1', function(req, res) {
  res.json({
    "employees": [
      { "firstName":"John"  , "lastName":"Doe"   },
      { "firstName":"Anna"  , "lastName":"Smith" },
      { "firstName":"Peter" , "lastName":"Jones" }
    ]
  })
});

app.listen(PORT);

You can implement an authentication (with JWT for example), but if browser has a token it's going to see that json anyway. I don't know if this is a restful api but, if not, you can send only post requests (like graphql)

There's no way to guarantee what you want to do.

You can use CSRF tokens and that will help if someone just points their browser at the endpoint.

Looks like you are using Express - something like this would help with CSRF: http://expressjs.com/en/resources/middleware/csurf.html

Generally if you are taking a "front-end" request from javascript or something in a browser, you can't prevent people from getting to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM