Firebase

How to handle Firebase Authentication token expiration in a Flutter app?

Discover how to tackle Firebase Authentication token expiration in your Flutter app. This guide offers hands-on solutions for a smooth user experience.

Developer profile skeleton
a developer thinking

Overview

Keeping Firebase Authentication token expiration under control in a Flutter app is key to a smooth user experience and secure interactions. When a user's token runs out, the app needs to refresh it quickly so users keep access to important features. This means knowing how tokens work, using Firebase's built-in tools for managing them, and setting up ways to refresh tokens automatically. Plus, it's vital to deal with unexpected issues like network problems or session timeouts without a hitch. Good token management keeps the app safe and ensures users have a seamless time.

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 handle Firebase Authentication token expiration in a Flutter app?

Step 1: Setup Firebase Authentication

First things first, make sure your Flutter project is all set up with Firebase, and that Firebase Authentication is ready to go.

  • Follow the Firebase documentation to add Firebase to your Flutter project.
  • Enable the sign-in methods you need (like Email/Password, Google sign-in, etc.) on the Firebase console.

Step 2: Add Firestore and Firebase Auth Packages

Next, let's add the necessary dependencies in the pubspec.yaml file:

dependencies:
  firebase_core: latest_version
  firebase_auth: latest_version

Then, run flutter pub get to install the packages. Easy peasy, right?

Step 3: Initialize Firebase in the App

Now, let's initialize Firebase in the main.dart file:

import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

Step 4: Implement Firebase Authentication

Time to create functions for signing in, signing up, and handling user authentication:

import 'package:firebase_auth/firebase_auth.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;

Future<User?> registerWithEmailPassword(String email, String password) async {
  UserCredential userCredential = await _auth.createUserWithEmailAndPassword(
    email: email,
    password: password,
  );
  return userCredential.user;
}

Future<User?> signInWithEmailPassword(String email, String password) async {
  UserCredential userCredential = await _auth.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
  return userCredential.user;
}

Step 5: Listen for Authentication State Changes

Let's set up an authentication state listener to keep an eye on user sign-ins and sign-outs:

_auth.authStateChanges().listen((User? user) {
  if (user == null) {
    print('User is currently signed out!');
  } else {
    print('User is signed in!');
  }
});

Step 6: Handle Token Expiration

Firebase usually refreshes the user's ID token when it expires. But, just in case, let's add some code to handle scenarios where this might fail:

Future<void> signOut() async {
  await _auth.signOut();
}

Future<void> refreshToken(User user) async {
  try {
    await user.getIdToken(true); // Forces token refresh.
  } catch (e) {
    await signOut(); // Sign out if token refresh fails.
    print('Token refresh failed: $e');
  }
}

void checkAndRefreshToken() async {
  User? user = _auth.currentUser;
  if (user != null) {
    user.getIdTokenResult(true).then((idTokenResult) {
      DateTime expirationTime = idTokenResult.expirationTime as DateTime;
      Duration diff = expirationTime.difference(DateTime.now());
      
      if (diff.inMinutes < 10) { // If token is about to expire in next 10 minutes
        refreshToken(user);
      }
    });
  }
}

Step 7: Schedule Periodic Token Checks

Finally, let's use Timer to regularly check and refresh the token:

import 'dart:async';

void main() {
  Timer.periodic(Duration(minutes: 5), (timer) {
    checkAndRefreshToken();
  });

  runApp(MyApp());
}

This way, your tokens will be refreshed periodically. And there you have it!

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.