1

I am using cloud functions for firebase and trying to build a kind of REST API.

What I want is to allow only one origin to make the request to my REST API. For example, I don't want to be allowed to request my API from postman or something like that but only from mywebsite.com.

So Cloud Functions for Firebase is a node js env so this is my current situation :

const cors = require('cors')({origin: "http://mywebsite.com"});

exports.addMessage = functions.https.onRequest((req, res) => {
  const textMessage = req.query.text;
  cors(req,res,()=>{
   firebase.database().ref('/messages').push({original: original}).then(snapshot => {
   
    res.status(200).send(textMessage)
    //this send result to every origin that requested whereas I want to allow only mywebsite.com
  });
  })
  
});

Any solution ?

Thanks

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jack
  • 157
  • 1
  • 3
  • 8
  • 1
    var cors = require('cors') var app = express() var corsOptions = { origin: 'http://mywebsite.com', optionsSuccessStatus: 200 } app.get('/products/:id', cors(corsOptions), function (req, res, next) { res.json({msg: 'This is CORS-enabled for only example.com.'}) }) – Adiii Jun 13 '17 at 13:44
  • Thanks. I've tried but there is no difference still can request from my postman and get the result from anywhere – Jack Jun 13 '17 at 14:24
  • 1
    CORS configuration won’t prevent the server from accepting requests based on the value of the Origin request header. You can’t do that just through CORS configuration. When you configure CORS support on a server, all that the server does differently is just to send the Access-Control-Allow-Origin response header and other CORS response headers. Actual enforcement of CORS restrictions is done only by browsers. It’s not enforced by servers. CORS doesn‘t prevent any other clients from being able to successfully retrieve resources. – sideshowbarker Jun 13 '17 at 14:39
  • For a more-detailed explanation of why you can’t block non-browser clients with server-side CORS settings, see https://stackoverflow.com/questions/43432743/will-asp-net-core-cors-policy-prevent-resource-access-from-non-browser-requests/43432787#43432787 and https://stackoverflow.com/questions/44034905/why-isnt-rack-cors-filtering-incoming-requests-according-to-rspec/44035843#44035843 – sideshowbarker Jun 13 '17 at 14:40
  • @sideshowbarker thanks for the info. Do you have an idea about how i can process to prevent third person/app to request my api ? – Jack Jun 13 '17 at 14:48
  • @Jack set up some type of authentication backend using https://www.npmjs.com/package/express-authentication or such – sideshowbarker Jun 13 '17 at 14:50

1 Answers1

0

simply use

res.header('Access-Control-Allow-Origin', 'http://mywebsite.com');

before sending response back to client would do.