3.5 Hours

5. Authentication: Users, Sessions & OAuth

Auth

Production-Grade Authentication Out of the Box

Firebase Authentication provides a complete identity management system. It handles email/password sign-up, magic links, SMS OTP, social OAuth providers (Google, GitHub, Apple, Twitter, and 20+ more), and anonymous sign-in — all configurable from the Firebase Console with no backend code required.

Firebase Authentication is built on Google Cloud IAM. It stores users in a secure, managed identity store. It issues JWT tokens for authentication. The service handles password hashing, email verification, OAuth flows, and session management. It's designed to be secure by default — passwords are hashed with bcrypt, emails are verified before allowing access, and refresh tokens are rotated on every use. The JWT contains the user's ID, email, and any custom claims you add. This JWT is used by Security Rules to identify the user. Understanding Authentication is essential for building secure applications. You'll need to configure your auth settings, set up OAuth providers, and handle user sessions properly.

Auth Flow & JWT Architecture

When a user signs in, Firebase issues two tokens: an ID Token (JWT) and a Refresh Token. The ID Token is short-lived (~1 hour) and is sent with every API request. It contains the user's id, email, and custom claims. The Refresh Token is long-lived and stored securely. It's used to obtain a new ID Token after it expires. The Firebase SDK handles token management automatically. It stores the session in localStorage by default and refreshes the token when it expires. For server-side applications, you can use the Firebase Admin SDK. Understanding this flow helps you debug auth issues and build secure authentication.

ID Token (JWT)

Short-lived (~1 hour). Sent with every API request. Contains the user's id, email, and custom claims. Verified without a database roundtrip.

Refresh Token

Long-lived, stored in localStorage or cookies. Used to obtain a new ID Token after it expires. Single-use and rotated on every refresh for security.

JavaScript
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth';

const auth = getAuth();

// Sign up with email and password
createUserWithEmailAndPassword(auth, 'user@example.com', 'secure-password')
  .then((userCredential) => {
    const user = userCredential.user;
    console.log('User signed up:', user.email);
  })
  .catch((error) => {
    console.error('Error:', error.message);
  });

// Sign in with email and password
signInWithEmailAndPassword(auth, 'user@example.com', 'secure-password')
  .then((userCredential) => {
    const user = userCredential.user;
    console.log('User signed in:', user.email);
  })
  .catch((error) => {
    console.error('Error:', error.message);
  });

OAuth Providers

OAuth providers simplify authentication for users. Google, GitHub, Apple, Twitter, and 20+ other providers are supported out of the box. To set up OAuth, configure your provider's client ID and secret in the Firebase Console. The flow is: user clicks Sign in with Google, they're redirected to Google's login page, they approve the request, they're redirected back to your app with an auth code, and your app exchanges the code for a session. The Firebase SDK handles this flow for you. You just call signInWithPopup or signInWithRedirect with the provider. The user's profile data is stored in the user object. Remember to handle the redirect flow for mobile and server-side apps.

JavaScript
import { getAuth, signInWithPopup, GoogleAuthProvider, signOut } from 'firebase/auth';

const auth = getAuth();
const provider = new GoogleAuthProvider();

// Sign in with Google popup
signInWithPopup(auth, provider)
  .then((result) => {
    const user = result.user;
    console.log('User signed in:', user.displayName);
  })
  .catch((error) => {
    console.error('Error:', error.message);
  });

// Sign out
signOut(auth).then(() => {
  console.log('User signed out');
});
Auth State Persistence:The Firebase SDK persists auth state by default. Users remain signed in across page reloads. Configure persistence type for different storage options.

Custom Claims & Server-Side Auth

Custom claims allow you to add application-specific data to the user's token. This is useful for role-based access control. Claims are set server-side using the Firebase Admin SDK. They're included in the ID Token and available in Security Rules. For example, you can add an admin claim to grant administrative privileges. Custom claims are cached in the token for performance. They can take up to 5 minutes to propagate. Use custom claims for coarse-grained permissions. For fine-grained permissions, use Firestore data. Server-side authentication uses the Firebase Admin SDK. It validates ID Tokens and provides access to all services without Security Rules.

JavaScript
// Admin SDK - Server-side
import { initializeApp } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';

const adminApp = initializeApp();
const adminAuth = getAuth(adminApp);

// Set custom claims
await adminAuth.setCustomUserClaims('user-uid', {
  admin: true,
  role: 'moderator'
});

// Verify ID Token on server
const decodedToken = await adminAuth.verifyIdToken(idToken);
const uid = decodedToken.uid;
const isAdmin = decodedToken.admin || false;

Security Best Practices

Authentication security is critical for any application. Enable email verification to prevent spam signups. Set password strength requirements. Use the PKCE flow for OAuth in server-side rendered apps. Never trust client-provided user IDs — always use auth.uid in Security Rules. Audit authentication events in Firebase Console. Use HTTPS for all requests. Store session tokens securely. Implement rate limiting on auth endpoints. These practices protect your users' accounts and your data. Monitor auth events for suspicious activity. Use multi-factor authentication for sensitive applications.

  • Enable email verification — prevents spam signups and verifies ownership.
  • Set password strength requirements in Auth settings.
  • Use PKCE flow for OAuth in server-side rendered apps to prevent token interception.
  • Never trust client-provided user IDs — always use auth.uid in Security Rules.
  • Audit with Firebase Console — monitor auth events for suspicious activity.

Knowledge Check

Ready to test your understanding of 5. Authentication: Users, Sessions & OAuth?

Back