Firebase

How to secure Firebase Cloud Functions HTTP endpoints?

Discover practical ways to safeguard your Firebase Cloud Functions HTTP endpoints. Protect web services and keep data safe by following tried-and-true practices.

Developer profile skeleton
a developer thinking

Overview

Securing Firebase Cloud Functions HTTP endpoints is essential to protect backend services and user data from unauthorized access and harmful attacks. This means you need to set up authentication and authorization steps, use Firebase Authentication to verify users, and apply IAM roles to manage permissions. Other key security practices involve establishing CORS policies, checking incoming requests, and using security rules. When done correctly, securing your HTTP endpoints ensures that only valid requests are allowed, keeping your application and its users safe and sound.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to secure Firebase Cloud Functions HTTP endpoints?

Step 1: Set up Firebase Authentication

First things first, make sure Firebase Authentication is turned on in the Firebase Console. Head over to the Authentication section and set up the sign-in methods you plan to use.

Step 2: Import Required Modules

In your index.js or functions.js, bring in the Firebase Admin SDK and Firebase Functions SDK.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

Step 3: Write an Authentication Middleware

Create a middleware function to check ID tokens from clients. This makes sure the incoming request is legit.

async function authenticate(req, res, next) {
    if (!req.headers.authorization || !req.headers.authorization.startsWith('Bearer ')) {
        res.status(403).send('Unauthorized');
        return;
    }

    const token = req.headers.authorization.split('Bearer ')[1];

    try {
        await admin.auth().verifyIdToken(token);
        next();
    } catch (error) {
        res.status(403).send('Unauthorized');
    }
}

Step 4: Integrate Middleware with HTTP Function

Wrap your HTTP endpoint with the authentication middleware so all requests get authenticated first.

exports.secureEndpoint = functions.https.onRequest((req, res) => {
    authenticate(req, res, () => {
        // Your secure function logic here
        res.status(200).send('Request authenticated and fulfilled');
    });
});

Step 5: Set Up CORS for Secure Access

Make sure CORS is set up to control access to your function. If you haven't already, install the cors package via npm:

npm install cors

Then, integrate CORS in your function:

const cors = require('cors')({ origin: true });

exports.secureEndpoint = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        authenticate(req, res, () => {
            // Your secure function logic here
            res.status(200).send('Request authenticated and fulfilled');
        });
    });
});

Step 6: Handle Authorization (Optional)

If you need more than just authentication, like checking user roles or permissions, do it within your function logic:

async function authorize(req, res, next) {
    const token = req.headers.authorization.split('Bearer ')[1];
    try {
        const decodedToken = await admin.auth().verifyIdToken(token);
        const userId = decodedToken.uid;

        // For example, checking user role or permission:
        const userRecord = await admin.auth().getUser(userId);
        if (userRecord.customClaims && userRecord.customClaims.admin === true) {
            next();
        } else {
            res.status(403).send('Forbidden');
        }
    } catch (error) {
        res.status(403).send('Forbidden');
    }
}

exports.secureEndpoint = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        authenticate(req, res, () => {
            authorize(req, res, () => {
                // Your secure function logic here
                res.status(200).send('Request authenticated and authorized');
            });
        });
    });
});

Step 7: Test Your Endpoint

Test the secure endpoint with an authenticated request using a tool like Postman or through your front-end app. Make sure the request includes a valid Firebase ID Token in the Authorization header.

GET /secureEndpoint HTTP/1.1
Host: your-cloud-functions-url
Authorization: Bearer YOUR_FIREBASE_ID_TOKEN

All requests without a valid token should get a 403 Unauthorized or Forbidden response based on the error handling.

Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.