Samuel Hill Samuel Hill - 1 month ago 18
Node.js Question

Allow requests only from my chrome extension

I have a NodeJS server set up and working with Express, hosted on DigitalOcean. I'm making GET calls to it from within my Chrome extension. It currently works great, but I'd like to tighten down the security on the following middleware:

// Add headers
app.use(function (req, res, next) {

// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*'); //todo: change this

// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);

// Pass to next layer of middleware
next();
});


The problem is, I think the
*
in
access-control-allow-origin
is letting anyone hit my endpoint. Is there a way to only allow calls from my Chrome extension, and not anywhere else?

Thanks in advance,
Sam

Answer

Since your extension will be installed on different computers with different IP addresses, there is no way to stop others from hitting your server. And certainly not with Access-Control-Allow-Origin header, since it only works in a browser environment and in page context, not extension context, which is governed by different mechanism. Any application that can talk through HTTP will be able to reach your server. The only thing that you can do is to send some identification information through headers, and then you can verify on the server that the request is sent from your extension and process it. Otherwise, you can return 503 Service Unavailable status code in your response. Of course, this solution can be worked around, by it implies knowing that your server does exist and knowing the IP address of it, and then also knowing the header and the value that should be sent.