Firebase

How to use Firebase Authentication with custom tokens?

Discover how to seamlessly add Firebase Authentication with custom tokens into your app. Follow this step-by-step guide to ensure secure user login using Firebase and custom tokens.

Developer profile skeleton
a developer thinking

Overview

Firebase Authentication using custom tokens lets you blend your own authentication system with Firebase's. It's all about creating a special token on your server, uniquely marking a user in your setup. Afterward, you swap this custom token for a Firebase ID token, giving users entry to Firebase goodies. Perfect for demanding scenarios needing precise user control, custom tokens grant flexibility to handle roles, permissions, and current user records. This approach guarantees a safe, effortless fusion between your systems and Firebase's reliable authentication tools.

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 use Firebase Authentication with custom tokens?

Step 1: Set up Firebase in your project

  1. First things first, create a Firebase project in the Firebase Console.
  2. Add your web, iOS, or Android app to the Firebase project.
  3. Follow Firebase's setup instructions to integrate the SDK into your project. This means adding configuration files and initializing Firebase in your app code.

Step 2: Setup Server Environment

  1. Make sure you have Node.js installed for server-side scripting.

  2. Install the Firebase Admin SDK using npm:
    ```bash
    npm install firebase-admin --save
    ```

  3. Initialize Firebase Admin in your server code:
    ```javascript
    const admin = require('firebase-admin');
    const serviceAccount = require('path-to-serviceAccountKey.json');

    admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
    });
    ```

Step 3: Create Custom Tokens on Server

  1. Once the Firebase Admin SDK is up and running, generate Firebase custom tokens on your server:
    ```javascript
    const uid = 'some-unique-user-id';

    admin.auth().createCustomToken(uid)
    .then((customToken) => {
    // Send token back to client or use it as needed
    })
    .catch((error) => {
    console.log("Error creating custom token:", error);
    });
    ```

  2. If you want, you can include custom claims:
    ```javascript
    const additionalClaims = {
    premiumAccount: true
    };

    admin.auth().createCustomToken(uid, additionalClaims)
    .then((customToken) => {
    // Send token back to client or use it as needed
    })
    .catch((error) => {
    console.log("Error creating custom token:", error);
    });
    ```

Step 4: Pass Tokens to Client

  1. Send the custom token from the server to the client. You can do this through an HTTP response, WebSocket, or any other method that works for your app.

Step 5: Authenticate Client with Custom Token

  1. On the client-side (whether it's iOS, Android, or Web), authenticate using the Firebase custom token you got from the server:
    ```javascript
    firebase.auth().signInWithCustomToken(customToken)
    .then((userCredential) => {
    // User signed in successfully
    const user = userCredential.user;
    })
    .catch((error) => {
    // Handle Errors
    console.error("Error during sign in with custom token:", error);
    });
    ```

Step 6: Verify and Use Authenticated User

  1. Once authenticated, Firebase gives you user information for subsequent operations.

  2. Access the authenticated user details:
    ```javascript
    const currentUser = firebase.auth().currentUser;

    if (currentUser) {
    console.log("User ID:", currentUser.uid);
    } else {
    console.log("No user is signed in.");
    }
    ```

  3. Use the authenticated user for application-specific functionalities like accessing the database, Storage, etc., with the security rules applied based on user authentication.

Step 7: Handle Token Expiry and Errors

  1. Handle token expiration or any other errors properly by setting up error handling mechanisms:
    ```javascript
    firebase.auth().signInWithCustomToken(customToken)
    .catch((error) => {
    if (error.code === 'auth/invalid-custom-token') {
    console.error("The token you provided is not valid.");
    } else if (error.code === 'auth/custom-token-mismatch') {
    console.error("The token you provided does not match the expected format.");
    } else {
    console.error("An unknown error occurred:", error);
    }
    });
    ```

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.