Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 31 ยท Authentication

OAuth Providers, Magic Links and JWTs

Add Google and GitHub sign-in, magic links and OTP codes, then learn how JWT access tokens, refresh tokens and expiry work, with a runnable JWT stand-in.

Passwords are not the only way in. Many users prefer "Continue with Google", and others like a one-time link sent to their inbox. Both Firebase Auth and Supabase Auth support these, and they all end the same way: the user holds a signed token that proves who they are. Understanding that token, a JWT, helps you debug sign-in problems and write correct rules.

The provider setup and SDK calls here are read-only because they need real accounts. The JWT part is different: you can sign, decode and verify a token right on this page with a Node.js stand-in. It builds on Email and Password Sign-In.

OAuth sign-in with Google or GitHub

With OAuth, your app never sees the user's Google password. The user signs in at Google, and Google tells your auth service who they are. The BaaS then creates (or finds) a user and issues its own tokens.

sequenceDiagram
    participant U as User
    participant A as Your app
    participant P as Provider (Google)
    participant S as Auth service
    U->>A: Click "Continue with Google"
    A->>P: Redirect or popup
    U->>P: Approve access
    P->>S: Authorization code
    S->>P: Exchange for identity
    S->>A: Session with access and refresh tokens

The provider proves identity; the auth service turns it into a session for your app.

To use a provider you enable it in the console or dashboard and paste in the client ID and secret you create at the provider. You also register your redirect URL there. Redirect URLs must match exactly, which is the most common source of errors.

JavaScript
// Firebase (read-only)
import { GoogleAuthProvider, signInWithPopup, getRedirectResult } from "firebase/auth";

const provider = new GoogleAuthProvider();
const result = await signInWithPopup(auth, provider);
console.log(result.user.displayName, result.user.photoURL);
JavaScript
// Supabase (read-only)
const { data, error } = await supabase.auth.signInWithOAuth({
  provider: "github",
  options: { redirectTo: "https://example.com/auth/callback" },
});
// The browser leaves your page; after approval it returns to redirectTo with a session.

Popups are simple on desktop; redirects are more reliable on mobile browsers and in-app web views.

More providers and what changes

Firebase supports many identity providers: Google, Facebook, Twitter/X, GitHub, Apple, Microsoft and Yahoo, plus email/password, phone numbers and anonymous accounts. Supabase supports a similar list (Google, GitHub, Apple, Azure, Facebook, Twitter/X, Discord and more). The flow is always the one above; only the setup differs:

Provider What you create at the provider Notes
Google OAuth client ID and secret Easiest; works in popup and redirect modes
GitHub An OAuth App with the callback URL Popular for developer tools; users may hide their email
Facebook A Facebook app with an app ID and secret Needs the Facebook Login product and an app in live mode
Twitter/X A developer app with API key and secret Access to the email address must be requested explicitly
Apple Services ID, key and team ID Required by the App Store if you offer other social logins on iOS
Microsoft An Entra (Azure) app registration Handles work, school and personal accounts
JavaScript
// Firebase: the same shape for every provider (read-only)
import { FacebookAuthProvider, GithubAuthProvider, OAuthProvider, signInWithPopup } from "firebase/auth";

await signInWithPopup(auth, new FacebookAuthProvider());
await signInWithPopup(auth, new GithubAuthProvider());
await signInWithPopup(auth, new OAuthProvider("microsoft.com"));  // also "apple.com", "yahoo.com"

For every provider you must enable it in the console, paste the client ID and secret, add your domain to the authorized domains, and register the redirect URL the console shows. Never paste a provider secret into front-end code. If a second provider returns an email that already belongs to an account, Firebase may raise auth/account-exists-with-different-credential; you resolve it by signing in with the first method and linking the second with linkWithPopup.

Custom authentication tokens

If you already have your own login system (a company directory, a legacy database, a game server), you can keep it and still use Firebase for data. Your trusted server verifies the user, then mints a custom token with the Admin SDK, and the client exchanges it for a normal Firebase session:

JavaScript
// Server, for example a Cloud Function (read-only)
import { getAuth } from "firebase-admin/auth";

export const authenticateUser = onCall(async (request) => {
  const user = await verifyAgainstLegacySystem(request.data.username, request.data.password);
  if (!user) throw new HttpsError("unauthenticated", "Wrong credentials");
  const token = await getAuth().createCustomToken(user.id, { tier: user.tier });  // extra claims
  return { token };
});
JavaScript
// Client (read-only)
import { signInWithCustomToken } from "firebase/auth";
await signInWithCustomToken(auth, tokenFromYourServer);

The custom token is a JWT signed with your service account and valid for one hour; the ID token the client gets afterwards carries your uid and claims, so security rules work as usual. Protect the service account and never mint tokens for unverified users. Supabase's equivalent is signing your own JWT with the project's JWT secret, or using its third-party auth integration.

A magic link is a sign-in link emailed to the user. Clicking it proves control of the mailbox, so no password is needed. An OTP (one-time password) is the same idea with a short code the user types in, which also works for phone numbers by SMS.

JavaScript
// Supabase (read-only)
await supabase.auth.signInWithOtp({
  email: "[email protected]",
  options: { emailRedirectTo: "https://example.com/welcome" },
});
// With a code instead of a link:
const { data, error } = await supabase.auth.verifyOtp({
  email: "[email protected]",
  token: "123456",
  type: "email",
});
JavaScript
// Firebase email link (read-only)
import { sendSignInLinkToEmail, isSignInWithEmailLink, signInWithEmailLink } from "firebase/auth";

await sendSignInLinkToEmail(auth, email, {
  url: "https://example.com/finish-sign-in",
  handleCodeInApp: true,
});
// On the landing page:
if (isSignInWithEmailLink(auth, window.location.href)) {
  await signInWithEmailLink(auth, email, window.location.href);
}

Codes and links must be single-use and expire quickly. The platforms enforce that, and limit how often you can request one, to stop abuse.

Ways to sign in

Password Remembered secret, stored as a hash.
OAuth A provider vouches for the user.
Magic link A one-time link in the inbox.
OTP code A short code by email or SMS.

Every method ends in the same thing: a signed token.

1 / 2

Anatomy of a JWT

Both platforms issue JSON Web Tokens. A JWT is three base64url-encoded parts joined by dots: header.payload.signature.

  • The header names the signing algorithm, for example {"alg":"HS256","typ":"JWT"}. Supabase's own tokens are signed with a secret key, while Firebase ID tokens are signed with Google's private key (RS256) so anyone can verify them with Google's public keys.
  • The payload holds claims about the user and the token. Standard ones: sub (the user ID), iat (issued at), exp (expires at), iss (who issued it) and aud (who it is for). Supabase adds role and email, Firebase adds uid-related fields and firebase.sign_in_provider.
  • The signature covers the header and payload. If anybody changes a single character, verification fails.

A JWT payload is encoded, not encrypted. Anyone holding the token can read it. Never put secrets in claims, and never treat a decoded but unverified token as proof of anything.

Access tokens, ID tokens and refresh tokens

  • The access token (Supabase) or ID token (Firebase) is sent with each request. It is short-lived, typically about an hour, so a stolen one stops working soon.
  • The refresh token is long-lived and opaque. The SDK trades it for a new access token in the background before expiry. Supabase rotates refresh tokens on use; Firebase keeps one until the user signs out or the account changes.
  • On the web, SDKs refresh automatically. After a server-side change such as a new role, the old token still carries the old claims until it is refreshed, which we will meet in Users, Roles and Custom Claims.

On a backend that you write yourself, you must verify tokens on every request: check the signature, that exp is in the future, and that iss and aud match. Firebase offers the Admin SDK for this (verifyIdToken); for Supabase you verify with the project's signing key or ask the auth server. Never accept a token just because it decodes.

Stand-in: sign, decode and verify a JWT

This program builds a token with HS256 (HMAC-SHA256) using node:crypto, decodes it without verifying, then verifies it and tests tampering and expiry. The real services use their own keys and libraries, but the structure is the same. The Authentication: Sessions and JWT lesson goes deeper on the Node.js side.

Node.js Stand-in: sign, decode and verify a JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The decoded payload prints without any secret, which shows why claims must never hold private data. The forged token fails because the signature no longer matches the changed payload.

A second stand-in shows the refresh idea: a short-lived access token renewed from a refresh token that is rotated on each use, so reusing an old one is detected.

Node.js Stand-in: refresh token rotation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Supabase implements rotation with a short reuse window to tolerate network retries; the stand-in is stricter than the real one, which is fine for learning.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In OAuth sign-in with Google, who sees the user's Google password?

    The user signs in on the provider's own page. Your app receives an identity, never the password.
  2. 2. What are the three parts of a JWT?

    A JWT is header.payload.signature, each base64url encoded.
  3. 3. Why must you never trust a decoded JWT without verifying it?

    The payload is readable and forgeable. Only a valid signature from the trusted issuer, plus checks like exp, makes it trustworthy.
  4. 4. Why are access tokens short-lived?

    A short lifetime limits the damage of a leaked token, and the refresh token renews it quietly.
  5. 5. What should happen when a rotated refresh token is used a second time?

    A used token showing up again suggests it was copied, so revoking is the safe response.

Summary

  • OAuth lets a provider such as Google or GitHub vouch for a user; magic links and OTP codes prove control of an email or phone.
  • All methods end in signed tokens: a short-lived access (ID) token and a long-lived refresh token.
  • A JWT is header.payload.signature. The payload is readable by anyone, so verify the signature, exp, iss and aud, and keep secrets out of claims.
  • Redirect URLs must match exactly what you registered with the provider.
  • Rotating refresh tokens let you detect theft by spotting reuse.

Next: Users, Roles and Custom Claims