Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js limit api access to only pages from the same website

I am using parse.com to host my app. I have built a simple api that feeds back json. The url is simple like so: http://websitename.parseapp.com/api/new/1/10. Right now, I have my api publicly visible, but I want to limit the access so only pages from that same domain name can access it only. How can I achieve this with express.js?

Here is a sample code of what I have:

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

// Global app configuration section
app.set('views', 'cloud/views');  // Specify the folder to find templates
app.set('view engine', 'ejs');    // Set the template engine
app.use(express.bodyParser());    // Middleware for reading request body

// This is an example of hooking up a request handler with a specific request
// path and HTTP verb using the Express routing API.
app.get('/api/:page/:from/:to', function(req, res) {
  res.render('hello', { message: 'Congrats, you just set up your app!' });
});

// This line is required to make Express respond to http requests.
app.listen();
like image 532
Max Pain Avatar asked Sep 27 '22 08:09

Max Pain


1 Answers

You want to prevent Cross-origin resource sharing, which is already prevented by express.js. To allow it from certain sites you have to set Access-Control-Allow-Origin and Access-Control-Allow-Headers (see here).

If you create a HTTP request to a different domain that the one you are there must be sent an Origin HTTP header including the requesting domain. Based on that the webserver decides wether to respond to the request or not.

If you want to prevent CORS from all domains but the one the site's hosted on: You don't have to do anything.

If you want to allow it from certain sites, alter the Access-Control-Allow-Origin-header to the domain names you want.

like image 174
Fabio Poloni Avatar answered Oct 11 '22 15:10

Fabio Poloni