惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
MongoDB | Blog
MongoDB | Blog
小众软件
小众软件
Apple Machine Learning Research
Apple Machine Learning Research
O
OpenAI News
酷 壳 – CoolShell
酷 壳 – CoolShell
The GitHub Blog
The GitHub Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 聂微东
Engineering at Meta
Engineering at Meta
W
WeLiveSecurity
Hacker News: Ask HN
Hacker News: Ask HN
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
F
Full Disclosure
AI
AI
罗磊的独立博客
博客园 - 【当耐特】
U
Unit 42
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
P
Palo Alto Networks Blog
博客园_首页
H
Help Net Security
量子位
月光博客
月光博客
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
博客园 - 司徒正美
F
Fortinet All Blogs
D
DataBreaches.Net
B
Blog RSS Feed
Webroot Blog
Webroot Blog
TaoSecurity Blog
TaoSecurity Blog
S
Secure Thoughts
爱范儿
爱范儿
I
InfoQ
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
C
CERT Recently Published Vulnerability Notes
Martin Fowler
Martin Fowler
Blog — PlanetScale
Blog — PlanetScale
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
S
Securelist

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Securing Your MCP Server with Firebase Auth: A Production Walkthrough
Dale Nguyen · 2026-05-16 · via DEV Community

Model Context Protocol (MCP) servers let AI assistants interact with real user data. That means auth isn't optional — it's the difference between a useful tool and a data breach. This post walks through exactly how Can Tax Pro secures its Python MCP server with Firebase Authentication, supporting both Firebase ID tokens (for direct access) and a custom OAuth 2.0 flow (for third-party clients like Claude.ai).


Architecture Overview

The system has three moving parts:

Browser / Claude.ai Client
       │
       │  Authorization: Bearer <token>
       ▼
  MCP Server (Python/FastMCP on Cloud Run)
       │
       │  Firebase Admin SDK
       ▼
  Firestore (data isolated by userId)

Enter fullscreen mode Exit fullscreen mode

Can Tax Pro MCP authentication flow demonstration

The MCP server accepts two token types:

  1. Firebase ID tokens — issued by Firebase Authentication, verified cryptographically
  2. Custom OAuth tokens (ctpo_*) — issued by the web app's OAuth server, stored as hashes in Firestore

The web app itself acts as the OAuth authorization server for third-party integrations.


Step 1: Initialize Firebase Admin SDK

The server initializes Firebase Admin once at startup, with environment-aware credential resolution:

# main.py
import firebase_admin
from firebase_admin import credentials, auth as firebase_auth, firestore

if not firebase_admin._apps:
    sa_json = os.environ.get("FIREBASE_SERVICE_ACCOUNT")
    project_id = os.environ.get("FIREBASE_PROJECT_ID")
    if sa_json:
        cred = credentials.Certificate(json.loads(sa_json))
        firebase_admin.initialize_app(cred, {"projectId": project_id})
    else:
        firebase_admin.initialize_app(options={"projectId": project_id})

Enter fullscreen mode Exit fullscreen mode

Locally: set FIREBASE_SERVICE_ACCOUNT to your service account JSON.
On Cloud Run: omit it entirely — the SDK picks up Application Default Credentials (ADC) automatically via Workload Identity.

This means no secrets in production. Your Cloud Run service account just needs the Firebase Admin SDK Administrator Service Agent IAM role.


Step 2: Token Resolution

Two resolver functions handle each token type:

OAuth Tokens (ctpo_*)

Custom tokens are never stored in plaintext. The server hashes them with SHA-256 and looks up the hash in Firestore:

def resolve_oauth_token(bearer_token: str) -> str:
    token_hash = hashlib.sha256(bearer_token.encode()).hexdigest()
    doc = db.collection("oauthTokens").document(token_hash).get()
    if not doc.exists:
        raise ValueError("Invalid or revoked OAuth token")
    data = doc.to_dict()
    expires_at = data.get("expiresAt")
    if expires_at and expires_at < datetime.now(timezone.utc):
        raise ValueError("OAuth token expired")
    return data["userId"]

Enter fullscreen mode Exit fullscreen mode

The Firestore document stores userId, expiresAt, clientId, and a refreshTokenHash. Revocation is instant — delete the document and the token stops working on the next request.

Firebase ID Tokens

Firebase handles the hard part:

def resolve_id_token(id_token: str) -> str:
    decoded = firebase_auth.verify_id_token(id_token)
    return decoded["uid"]

Enter fullscreen mode Exit fullscreen mode

verify_id_token checks the signature against Google's public keys and validates claims (expiry, issuer, audience). It caches the public keys locally so it doesn't make a network call on every request.


Step 3: The Auth Middleware

A Starlette BaseHTTPMiddleware wraps every request. It tries the OAuth path first, then falls back to Firebase ID tokens:

class AuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # Skip auth for public endpoints
        if request.url.path in _PUBLIC_PATHS:
            return await call_next(request)

        auth_header = request.headers.get("Authorization", "")
        if not auth_header.startswith("Bearer "):
            return Response(
                status_code=401,
                headers={"WWW-Authenticate": 'Bearer realm="tax-mcp"'},
            )

        token = auth_header.removeprefix("Bearer ").strip()
        token_set = _user_id_var.set("")

        try:
            # Try OAuth token first
            if token.startswith("ctpo_"):
                user_id = resolve_oauth_token(token)
            else:
                user_id = resolve_id_token(token)
            _user_id_var.set(user_id)
            return await call_next(request)
        except Exception as e:
            return Response(
                status_code=401,
                content=str(e),
                headers={"WWW-Authenticate": 'Bearer realm="tax-mcp"'},
            )
        finally:
            _user_id_var.reset(token_set)

Enter fullscreen mode Exit fullscreen mode

Public paths (/health, /.well-known/oauth-protected-resource) bypass auth — necessary for health checks and OAuth discovery.


Step 4: Thread-Safe User Context

Tools shouldn't take a user_id parameter — that would pollute every signature and make testing awkward. Instead, use a ContextVar to propagate identity through the async call stack:

# _context.py
from contextvars import ContextVar

_user_id_var: ContextVar[str] = ContextVar("user_id")

def get_user_id() -> str:
    try:
        return _user_id_var.get()
    except LookupError:
        raise RuntimeError("User context not set — request did not pass through auth middleware.")

Enter fullscreen mode Exit fullscreen mode

Every tool calls get_user_id() to scope its Firestore queries:

# tools/income.py
from .._context import get_user_id

@mcp.tool()
def list_income(tax_year_id: str) -> list[dict]:
    docs = (
        db.collection("users")
          .document(get_user_id())
          .collection("taxYears")
          .document(tax_year_id)
          .collection("incomeEntries")
          .stream()
    )
    return [{"id": d.id, **d.to_dict()} for d in docs]

Enter fullscreen mode Exit fullscreen mode

ContextVar is async-safe — each concurrent request gets its own context, so there's no cross-contamination between users even under high concurrency.

The middleware resets the var in a finally block, which is critical: without cleanup, the context leaks to the next request on a reused coroutine.


Step 5: The OAuth 2.0 Server (Web App Side)

For third-party clients (Claude.ai, etc.), the web app implements an OAuth 2.0 authorization server. Here's the flow:

1. Client → GET /oauth/authorize?client_id=...&code_challenge=...
2. User logs in (Firebase Auth)
3. Server → redirect with authorization_code
4. Client → POST /oauth/token with code + code_verifier
5. Server → { access_token: "ctpo_...", refresh_token: "ctpr_..." }

Enter fullscreen mode Exit fullscreen mode

Token generation (TypeScript, server-side):

// server/routes/oauth/token.post.ts
import { createHash, randomBytes } from "crypto";

const accessToken = "ctpo_" + randomBytes(32).toString("hex");
const tokenHash = createHash("sha256").update(accessToken).digest("hex");

await db.collection("oauthTokens").doc(tokenHash).set({
  userId: session.userId,
  clientId: session.clientId,
  expiresAt: new Date(Date.now() + 60 * 60 * 1000), // 1 hour
  createdAt: new Date(),
});

return { access_token: accessToken, token_type: "bearer", expires_in: 3600 };

Enter fullscreen mode Exit fullscreen mode

The ctpo_ prefix lets the MCP server route to the right resolver without trying Firebase first. Only the hash ever touches the database.

PKCE (Proof Key for Code Exchange) protects the authorization code flow. The client sends a code_challenge (SHA-256 of a random code_verifier) in step 1, then proves ownership by sending the raw code_verifier in step 4. The server hashes it and compares:

const verifierHash = createHash("sha256")
  .update(body.code_verifier)
  .digest("base64url");

if (verifierHash !== session.codeChallenge) {
  throw createError({ statusCode: 400, message: "Invalid code_verifier" });
}

Enter fullscreen mode Exit fullscreen mode


Step 6: Client-Side (Browser)

The Angular/Analog web app attaches Firebase ID tokens to outbound API requests via an HTTP interceptor:

// auth.interceptor.ts
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(Auth);
  return from(auth.currentUser?.getIdToken() ?? Promise.resolve(null)).pipe(
    switchMap((token) => {
      if (!token) return next(req);
      return next(req.clone({
        setHeaders: { Authorization: `Bearer ${token}` },
      }));
    }),
  );
};

Enter fullscreen mode Exit fullscreen mode

getIdToken() auto-refreshes the token when it's close to expiry, so you never send a stale JWT.


Step 7: Firestore Security Rules

The MCP server uses the Admin SDK, which bypasses all Firestore security rules. The get_user_id() context is your authorization layer. But rules provide defense-in-depth for direct client SDK access:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId}/{document=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
    match /oauthTokens/{tokenId} {
      allow read, write: if false; // Server-only
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

OAuth token documents are locked to server-only access. Users can never read or write them directly.


Step 8: OAuth Discovery Endpoint

Well-behaved OAuth clients (including Claude.ai) auto-discover server capabilities. Expose the RFC 9728 metadata endpoint:

@app.get("/.well-known/oauth-protected-resource")
async def oauth_protected_resource():
    return JSONResponse({
        "resource": "https://your-mcp-server.run.app",
        "authorization_servers": ["https://your-web-app.com"],
        "bearer_methods_supported": ["header"],
    })

Enter fullscreen mode Exit fullscreen mode

This tells clients where to find the authorization server and how to present tokens. It's a public endpoint (no auth required) — make sure it's in _PUBLIC_PATHS.


Step 9: Local Testing

Don't rely on a real Firebase project for unit tests. Seed a test token directly:

# test_auth.py
import hashlib
from firebase_admin import firestore
from datetime import datetime, timezone, timedelta

TEST_TOKEN = "ctpo_localtest_" + "a" * 48
TEST_TOKEN_HASH = hashlib.sha256(TEST_TOKEN.encode()).hexdigest()

def seed_test_token(db, user_id: str):
    db.collection("oauthTokens").document(TEST_TOKEN_HASH).set({
        "userId": user_id,
        "clientId": "test-client",
        "expiresAt": datetime.now(timezone.utc) + timedelta(hours=1),
    })

def cleanup(db):
    db.collection("oauthTokens").document(TEST_TOKEN_HASH).delete()

Enter fullscreen mode Exit fullscreen mode

Then test the three critical paths: no token → 401, invalid token → 401, valid token → 200.


Security Properties

Property How it's achieved
Token confidentiality Only SHA-256 hashes stored; raw tokens never persist
Revocation Delete Firestore doc; effective immediately
Expiry Enforced server-side on every request
Multi-user isolation ContextVar scopes every Firestore query to userId
No key management in prod Cloud Run Workload Identity + ADC
Code injection protection PKCE on OAuth code exchange
Defense in depth Firestore rules lock down client SDK access

Summary

Securing an MCP server with Firebase Auth comes down to four things:

  1. Middleware that validates tokens before any tool runs
  2. ContextVar to propagate user identity without polluting tool signatures
  3. Hash-only storage for custom OAuth tokens
  4. Workload Identity to eliminate service account key management in production

The dual-token design (Firebase ID tokens for direct use, custom OAuth tokens for third-party clients) keeps the server flexible while maintaining a single, auditable auth path. Every request either has a valid, unexpired token mapping to a real user, or it gets a 401.