Firebase

How to secure Firebase Realtime Database with token-based authentication?

Discover powerful ways to lock down your Firebase Realtime Database using token-based authentication. Simple tips to boost data privacy and keep unauthorized access at bay.

Developer profile skeleton
a developer thinking

Overview

Protecting data is vital for any app, especially when it involves sensitive user info. Firebase Realtime Database is widely used for storing and syncing data in real time. But making sure this data stays secure and accessible only to authorized users is a big deal. The key solution here is token-based authentication. This method checks the identity of users by validating a unique token given to them. The main focus here is on securing a Firebase Realtime Database using this type of authentication. It covers setting up authentication, configuring security rules, keeping data private, and managing who gets access.

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 Realtime Database with token-based authentication?

Step 1: Enable the Firebase Authentication

Alright, first things first. Head over to the Firebase Console, pick your project, and then navigate to the ‘Authentication’ section. Click on ‘Getting started’. In the Sign-in method tab, you’ll see a bunch of sign-in providers. Just toggle the enable slider for the ones you need.

If you’re looking to set up email and password authentication, here’s what you do:

  • Go to the Firebase console
  • On the left side, click Authentication
  • Click on the Sign-in method tab
  • Find Email/Password provider, flip the Enable switch, and hit Save

Step 2: Create Service Account & Download Key

Next up, you need to set up a service account and generate a new private key for your Firebase project. This key is crucial because your application server will use it to create custom authentication tokens.

  • Go to Firebase Console
  • Click on Project Settings
  • Click on the Service Accounts tab
  • Click on Generate New Private Key

The key file you download contains your project's credentials. Keep it safe! It has full access to all your Firebase project resources.

Step 3: Mint a Custom Token

Now, you need to mint a custom token on your application server using the Firebase Admin SDK. This token will be given to your clients so they can interact with Firebase.

Here’s a Node.js example to generate a custom token:

const admin = require('firebase-admin');

admin.initializeApp({
  credential: admin.credential.cert({
    projectId: '<PROJECT_ID>',
    clientEmail: 'foo@<PROJECT_ID>.iam.gserviceaccount.com',
    privateKey: '-----BEGIN PRIVATE KEY-----\n<KEY>\n-----END PRIVATE KEY-----\n'
  }),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
});

admin.auth().createCustomToken('<UID>')
  .then((customToken) => {
    // Send token back to client
  })
  .catch((error) => {
    console.log('Error creating custom token:', error);
  });

Make sure to replace <PROJECT_ID>, <DATABASE_NAME>, <UID>, and <KEY> with your specific project details.

Step 4: Pass Custom Token to the Client

Once your client gets the token, they can use it to authenticate with Firebase services. Here’s how you can sign in the client using this token with the Firebase SDK:

firebase.auth().signInWithCustomToken(customToken).catch((error) => {
  // Handle Errors here.
  var errorCode = error.code;
  var errorMessage = error.message;
  // ...
});

Step 5: Set Up Firebase Database Rules

To control who can access your Firebase Realtime Database, you’ll need to set up some security rules. These rules determine who can read and write data, validate the structure and size of the data, and more.

Go to the Database section in the Firebase console. Make sure you select "Realtime Database" and not "Cloud Firestore". Then click on the Rules tab. Set the read and write rules according to your needs.

Here’s an example rule that allows authenticated users to read and write:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

With these rules, only authenticated users can read and write data in your Firebase Realtime Database. Don’t forget to click "Publish" after you make changes to the rules.

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.