0
0
Firebasecloud~15 mins

Custom authentication tokens in Firebase - Deep Dive

Choose your learning style9 modes available
Overview - Custom authentication tokens
What is it?
Custom authentication tokens are special digital keys created by your server to let users sign in to Firebase securely. Instead of using Firebase's built-in sign-in methods, you create your own way to verify users and then generate these tokens. These tokens tell Firebase who the user is and what they are allowed to do. This helps connect your own user system with Firebase's services.
Why it matters
Without custom tokens, you would be limited to Firebase's default sign-in options, which might not fit your app's unique needs. Custom tokens let you use your own user database or special login methods, making your app more flexible and secure. This means users can access your app smoothly while you keep control over who they are and what they can do.
Where it fits
Before learning custom tokens, you should understand basic Firebase Authentication and how user sign-in works. After mastering custom tokens, you can explore advanced security rules, user management, and integrating Firebase with other backend systems.
Mental Model
Core Idea
Custom authentication tokens are secure, server-made keys that prove a user's identity to Firebase, allowing your app to control sign-in beyond default methods.
Think of it like...
It's like your own club issuing special membership cards to people you trust, which they then show at the club's entrance (Firebase) to get in, instead of using the club's standard guest list.
┌─────────────────────┐       ┌─────────────────────┐       ┌─────────────────────┐
│  Your Server        │       │  Firebase Auth      │       │  User's Device      │
│  (creates token)    │──────▶│  (verifies token)   │──────▶│  (signs in with     │
│                     │       │                     │       │   custom token)     │
└─────────────────────┘       └─────────────────────┘       └─────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Firebase Authentication Basics
🤔
Concept: Learn how Firebase Authentication works with default sign-in methods.
Firebase Authentication lets users sign in using email/password, Google, Facebook, and other providers. It manages user sessions and security automatically. This is the starting point before customizing sign-in.
Result
You can create users and let them sign in using Firebase's built-in options.
Knowing the default system helps you see why and when you need custom tokens to extend or replace it.
2
FoundationWhat Are Custom Authentication Tokens?
🤔
Concept: Introduce the idea of server-generated tokens for user identity.
Custom tokens are JWT (JSON Web Tokens) created by your trusted server. They include user info and a secret signature. Firebase accepts these tokens to sign users in as if they used a built-in method.
Result
You understand that custom tokens let your server control who can sign in.
Recognizing tokens as secure digital keys clarifies how Firebase trusts your server's user verification.
3
IntermediateCreating Custom Tokens on Your Server
🤔Before reading on: do you think the server needs to store user passwords to create custom tokens? Commit to your answer.
Concept: Learn how to generate tokens using Firebase Admin SDK without storing passwords.
Using Firebase Admin SDK, your server creates a token by providing a unique user ID and optional extra data. The SDK signs the token with your Firebase project's private key. This token is then sent to the client.
Result
You can produce valid tokens that Firebase will accept for sign-in.
Understanding that tokens are signed, not password-based, shows how security and privacy are maintained.
4
IntermediateUsing Custom Tokens on the Client Side
🤔Before reading on: do you think the client can modify the custom token before sending it to Firebase? Commit to your answer.
Concept: Learn how clients use the custom token to sign in with Firebase Authentication.
The client receives the custom token from your server and calls Firebase's signInWithCustomToken method. Firebase verifies the token's signature and signs the user in if valid.
Result
Users are signed in using your server's identity verification.
Knowing the client cannot alter tokens without breaking the signature explains why this method is secure.
5
IntermediateAdding Custom Claims for User Roles
🤔Before reading on: do you think custom claims can be changed by the client after sign-in? Commit to your answer.
Concept: Learn how to include extra user information in tokens to control access.
When creating tokens, your server can add custom claims like 'admin: true'. Firebase includes these claims in the user's ID token, which can be used in security rules to allow or deny actions.
Result
You can enforce fine-grained access control based on user roles.
Understanding custom claims empowers you to build secure, role-based features without extra database checks.
6
AdvancedRefreshing Tokens and Session Management
🤔Before reading on: do you think custom tokens last forever once issued? Commit to your answer.
Concept: Learn how Firebase handles token expiration and user sessions with custom tokens.
Custom tokens are short-lived and used only to sign in. After sign-in, Firebase issues ID tokens that refresh automatically. Your server must re-issue custom tokens only when users need to sign in again.
Result
You understand how sessions stay active without repeatedly creating custom tokens.
Knowing the difference between custom tokens and ID tokens prevents unnecessary token generation and improves performance.
7
ExpertSecurity Risks and Best Practices with Custom Tokens
🤔Before reading on: do you think exposing your Firebase Admin SDK credentials on the client is safe? Commit to your answer.
Concept: Explore security considerations and how to protect your token generation process.
Your server must keep Firebase Admin SDK credentials secret. Never generate tokens on the client. Use HTTPS to protect token transmission. Validate user identity thoroughly before issuing tokens to prevent unauthorized access.
Result
Your app remains secure against token forgery and misuse.
Understanding these risks helps you design a secure authentication system that protects user data and app integrity.
Under the Hood
Custom tokens are JWTs signed with your Firebase project's private key using the Firebase Admin SDK. When a client sends a token to Firebase Authentication, Firebase verifies the signature against its public key to confirm authenticity. The token contains a unique user ID and optional claims. After verification, Firebase creates a session and issues ID tokens for ongoing authentication. This process ensures that only tokens generated by your trusted server can sign users in.
Why designed this way?
Firebase designed custom tokens to allow developers to integrate their own user systems with Firebase securely. Using signed JWTs leverages a standard, widely supported format that is easy to verify and hard to forge. This design separates user identity verification (done by your server) from session management (handled by Firebase), providing flexibility and security. Alternatives like sharing passwords or client-side token creation were rejected due to security risks.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Your Server   │       │ Firebase Auth │       │ Client Device │
│ (creates JWT) │──────▶│ (verifies JWT)│──────▶│ (signs in)   │
│ Private Key   │       │ Public Key    │       │               │
└───────────────┘       └───────────────┘       └───────────────┘
        │                      │                      │
        │                      │                      │
        ▼                      ▼                      ▼
  Token signed          Token verified          User authenticated
  with secret           using public key        and session created
Myth Busters - 4 Common Misconceptions
Quick: Can clients safely generate their own custom tokens? Commit to yes or no.
Common Belief:Clients can create custom tokens themselves since they only need user info.
Tap to reveal reality
Reality:Only your trusted server should create custom tokens because it uses secret keys to sign them. Clients cannot safely generate tokens.
Why it matters:If clients create tokens, they can impersonate any user, breaking your app's security.
Quick: Do custom tokens last forever once issued? Commit to yes or no.
Common Belief:Custom tokens are permanent and can be reused anytime.
Tap to reveal reality
Reality:Custom tokens are short-lived and used only once to sign in. Firebase issues separate ID tokens for ongoing sessions.
Why it matters:Misunderstanding token lifespan can cause unnecessary token generation or session failures.
Quick: Can users change their custom claims after sign-in? Commit to yes or no.
Common Belief:Users can modify their roles or claims after signing in by editing tokens.
Tap to reveal reality
Reality:Custom claims are set by your server and cannot be changed by users. They are included in Firebase-issued ID tokens.
Why it matters:Assuming users can change claims risks trusting unauthorized access.
Quick: Is it safe to share Firebase Admin SDK credentials with frontend code? Commit to yes or no.
Common Belief:Sharing Admin SDK credentials on the client is fine for convenience.
Tap to reveal reality
Reality:Admin SDK credentials must remain secret on your server. Exposing them risks full control over your Firebase project.
Why it matters:Leaking credentials can lead to data breaches and loss of control.
Expert Zone
1
Custom tokens do not replace Firebase ID tokens; they only initiate sign-in. Understanding this separation is key to managing sessions properly.
2
Including too much data in custom claims can bloat tokens and slow down authentication; keep claims minimal and use Firestore or Realtime Database for extra user info.
3
Token revocation requires careful design since Firebase caches ID tokens; you must use Firebase's revoke API and force clients to refresh tokens.
When NOT to use
Avoid custom tokens if you can use Firebase's built-in providers like Google or email/password, as they are simpler and managed by Firebase. Use custom tokens only when you have an existing user system or need special authentication flows.
Production Patterns
In production, servers authenticate users via existing databases, then generate custom tokens with minimal claims. Clients use these tokens to sign in once, then rely on Firebase ID tokens. Security rules use custom claims for role-based access. Token revocation and refresh are handled via Firebase Admin SDK and client listeners.
Connections
JSON Web Tokens (JWT)
Custom tokens are a specific use of JWTs for authentication.
Understanding JWT structure and signing helps grasp how custom tokens securely prove identity.
OAuth 2.0
Both OAuth and custom tokens manage user identity and access but differ in flow and scope.
Knowing OAuth helps understand broader authentication frameworks and when custom tokens fit in.
Digital Signatures in Cryptography
Custom tokens rely on digital signatures to verify authenticity.
Grasping digital signatures clarifies why tokens can't be forged or altered without detection.
Common Pitfalls
#1Generating custom tokens on the client side.
Wrong approach:const token = createCustomToken(userId); // client-side code
Correct approach:const token = admin.auth().createCustomToken(userId); // server-side code
Root cause:Misunderstanding that token creation requires secret keys only available on the server.
#2Sending custom tokens over unsecured HTTP.
Wrong approach:fetch('http://myserver.com/getToken')
Correct approach:fetch('https://myserver.com/getToken')
Root cause:Ignoring the need for encrypted communication to protect tokens in transit.
#3Adding too much user data in custom claims.
Wrong approach:createCustomToken(userId, { profile: fullUserProfile });
Correct approach:createCustomToken(userId, { role: 'admin' });
Root cause:Not realizing token size affects performance and security; detailed data belongs in databases.
Key Takeaways
Custom authentication tokens let your server securely control user sign-in to Firebase beyond default methods.
They are signed JWTs created only on trusted servers and verified by Firebase to authenticate users.
Clients use these tokens once to sign in; Firebase then manages sessions with its own ID tokens.
Custom claims in tokens enable role-based access control without extra database queries.
Security depends on keeping token creation secrets on the server and using secure communication.