Skip to content

Firebase Admin SDK — Server-Side Authentication, User Management, and Token Verification

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Firebase Admin SDK. We cover key concepts, practical examples, and best practices to help you master this topic.

The Firebase Admin SDK enables server-side operations including ID token verification, user management, custom claims, Firestore admin access, and backend authentication for Firebase services.

What You'll Learn

  • Initializing the Admin SDK in Node.js and Python
  • Verifying Firebase ID tokens on the server
  • Managing users programmatically

Why It Matters

Client-side authentication is not trusted for server operations. The Admin SDK provides privileged access to manage users, verify tokens, and perform admin operations. DodaTech's backend services use the Admin SDK for all server-side Firebase operations.

flowchart LR
    A["Client App"] --> B["Firebase Auth SDK"]
    B --> C["ID Token"]
    C --> D["Backend Server"]
    D --> E["Admin SDK verifies token"]
    E --> F["Valid token"]
    E --> G["Invalid token"]
    F --> H["Authenticated request"]
    G --> I["Reject request"]

Code Examples

// Initialize Admin SDK (Node.js)
const admin = require('firebase-admin');

// Using service account file
const serviceAccount = require('./serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://project-id.firebaseio.com'
});

// Using environment variables
admin.initializeApp({
  credential: admin.credential.applicationDefault()
});
// Server-side authentication middleware
async function authenticateRequest(req, res, next) {
  const authHeader = req.headers.authorization;

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'No token provided' });
  }

  const idToken = authHeader.split('Bearer ')[1];

  try {
    const decodedToken = await admin.auth().verifyIdToken(idToken);
    req.user = {
      uid: decodedToken.uid,
      email: decodedToken.email,
      role: decodedToken.role,
      // Custom claims are available here
    };
    next();
  } catch (error) {
    console.error('Token verification failed:', error);
    return res.status(401).json({ error: 'Invalid token' });
  }
}

// Protected route
app.get('/api/secure-data', authenticateRequest, async (req, res) => {
  // req.user is available
  const data = await getDataForUser(req.user.uid);
  res.json(data);
});
# Python Admin SDK initialization and usage
import firebase_admin
from firebase_admin import credentials, auth, firestore

# Initialize
cred = credentials.Certificate('serviceAccountKey.json')
firebase_admin.initialize_app(cred)

# Verify ID token
def verify_token(id_token):
    try:
        decoded = auth.verify_id_token(id_token)
        return decoded['uid'], decoded.get('email')
    except auth.ExpiredIdTokenError:
        return None, 'Token expired'
    except auth.InvalidIdTokenError:
        return None, 'Invalid token'

# Flask middleware
@app.before_request
def authenticate():
    if request.path.startswith('/api/secure'):
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return {'error': 'Unauthorized'}, 401
        uid, error = verify_token(auth_header.split()[1])
        if error:
            return {'error': error}, 401
        request.user_id = uid
// Admin SDK: User management operations
const admin = require('firebase-admin');

// Create user
const userRecord = await admin.auth().createUser({
  email: 'alice@example.com',
  emailVerified: true,
  password: 'securePassword123',
  displayName: 'Alice Johnson',
  disabled: false
});
console.log('Created user:', userRecord.uid);

// Get user by email
const user = await admin.auth().getUserByEmail('alice@example.com');

// List all users
const listUsersResult = await admin.auth().listUsers(1000);
listUsersResult.users.forEach(user => {
  console.log(user.email, user.uid);
});

// Delete user
await admin.auth().deleteUser(user.uid);

// Disable user
await admin.auth().updateUser(user.uid, { disabled: true });

// Generate email verification link
const link = await admin.auth().generateEmailVerificationLink('alice@example.com');

// Generate password reset link
const resetLink = await admin.auth().generatePasswordResetLink('alice@example.com');

Common Mistakes

1. Exposing Service Account Credentials

Never commit service account JSON files or expose them to clients.

2. Not Verifying Tokens on Every Request

Server-side token verification must happen on every protected request.

3. Using the Client SDK Instead of Admin SDK on the Server

The client SDK does not have privileged access. Always use the Admin SDK.

4. Not Handling Token Expiration

ID tokens expire after 1 hour. Verify tokens on every request and handle expiration.

5. Ignoring Revoked Tokens

Check for token revocation if users are disabled or claims change.

Practice Questions

  1. What credential type does the Admin SDK use?
  2. How do you verify a Firebase ID token on the server?
  3. What is the difference between Admin SDK and Client SDK?
  4. How do you create a new user with the Admin SDK?
  5. How do you generate a password reset link programmatically?

Answers:

  1. A service account JSON key file or application default credentials.
  2. Call admin.auth().verifyIdToken(idToken).
  3. Admin SDK has privileged access for user management and bypasses security rules.
  4. Call admin.auth().createUser({ email, password }).
  5. Call admin.auth().generatePasswordResetLink(email).

Challenge: Build an Express API server that verifies Firebase ID tokens, implements role-based access control using custom claims, manages users via admin endpoints, and logs all authentication events. Include Rate Limiting and token revocation detection.

FAQ

Can I use the Admin SDK in client-side code?

No. The Admin SDK contains privileged credentials and must only run in trusted server environments.

How do I handle multiple Firebase projects with the Admin SDK?

Call admin.initializeApp multiple times with different app names: admin.initializeApp({...}, 'secondApp').

What is the difference between verifyIdToken and verifySessionCookie?

verifyIdToken verifies an ID token directly. verifySessionCookie verifies a session cookie created from an ID token for traditional session management.

How do I check for revoked tokens?

Set checkRevoked: true in verifyIdToken to check if the token has been revoked since issuance.

Can I use the Admin SDK with Firebase Extensions?

Yes. The Admin SDK works alongside Firebase Extensions. Some extensions may have their own Admin SDK setup.

Mini Project

Build a server-side authentication system with Express and the Firebase Admin SDK. Implement token verification middleware, user CRUD endpoints (admin only), custom claims management, session cookie support, and comprehensive error handling. Add automated tests for each endpoint.

What's Next

Explore Firebase Storage for secure file uploads, then learn about Storage security rules for access control.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro