Raphael Castro
Raphael Castro

Reputation: 1148

How do I get the origin URL of a Firebase Function request?

I am trying to build an application that executes logic ONLY if the origin URL is on allowlist. I am trying to get the origin URL inside of a Firebase Function using the following methods:

I tried using these from this stack overflow post:

req.get('Referrer')
req.get('Referer')
req.headers.referer
req.headers.referrer

All return undefined.

I tried to to put together this function from this stack overflow post:

function getOriginUrl(req: any) {
    return req.protocol + '://' + req.get('host') + req.originalUrl
}

This returns the base url of my cloud functions

https://us-central1-secured-1q4fq.cloudfunctions.net/

What I would actually like to see is the url that the post was made from. I am using this to make the post so I expect to see:

 https://reqbin.com

Upvotes: 1

Views: 1504

Answers (2)

Ashish
Ashish

Reputation: 6939

Maybe your trying to find how to block request sent by other website other than Your own website.

You can just use NPM library CORS.

For example your function want to allow only the request sent by localhost.

import * as cors from 'cors';
const corsHandler = cors({
  origin: [
    'http://localhost:4200',
    'http://127.0.0.1:4200',
    'http://localhost:5000',
    'http://127.0.0.1:5000',
  ],
});

Upvotes: 1

Donnald Cucharo
Donnald Cucharo

Reputation: 4126

The code is fine. Unlike on browsers where this header is automatically generated depending on the policy they're using, you'll need to set the Referrer header on reqbin (or any API tools like Postman) for example:

Referrer :  https://reqbin.com 

However there are security concerns on using this header as it can be easily manipulated. You should know this.

A better solution to secure your Firebase Functions is to use Firebase Auth. Here's a note:

HTTP requests don’t “come from a domain name”. HTTP requests appear to come from IP addresses whose traffic is routed across global networks. You could try to limit execution to certain source IPs, but those IP addresses aren’t guaranteed to identify the true source of the request.

If you want to protect your functions from execution, it’s better to require some other sort of security that identifies the originator of the request.

The Firebase team provides sample code that shows how to limit requests from only users authenticated with Firebase Authentication. You can also require the client to send a key that authorizes its use of a function.

Additional References:

Upvotes: 1

Related Questions