mcpField
F
firebase-auth

firebase-auth

github.com/jezweb安全1.1k363 次安装3 周前更新
代码仓库

关于 firebase-auth

面向使用 Firebase Authentication 的开发者,提供客户端与服务端身份验证实现指南。涵盖常见登录方式、令牌与会话管理、角色声明及安全注意事项。

主要功能

  1. 01邮箱密码与 OAuth 登录示例
  2. 02电话验证与多因素认证指南
  3. 03ID 令牌验证和会话 Cookie 管理
  4. 04自定义声明与受保护路由
  5. 05常见错误处理及安全建议

适用场景

  1. 01为应用添加注册、登录和密码重置
  2. 02在服务端验证用户令牌
  3. 03为管理功能配置角色并保护路由

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jezweb/claude-skills --skill firebase-auth

安装后在 Claude Code 中输入/firebase-auth确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

README.md
.claude-plugin/
plugin.json
rules/
firebase-auth.md
templates/
api-session.ts
auth-context.tsx
middleware.ts
protected-route.tsx

详细介绍

Firebase Authentication

状态:已可投入生产 最后更新:2026-01-25 依赖项:无(独立技能) 最新版本:[email protected]、[email protected]


快速入门(5 分钟)

1. 在 Firebase Console 中启用身份验证提供方
  1. 前往 Firebase Console > Authentication > Sign-in method
  2. 启用所需的提供方(Email/Password、Google 等)
  3. 使用客户端 ID/密钥配置 OAuth 提供方
2. 初始化 Firebase Auth(客户端)
// src/lib/firebase.ts
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  // ... other config
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
3. 初始化 Firebase Admin(服务端)
// src/lib/firebase-admin.ts
import { initializeApp, cert, getApps } from 'firebase-admin/app';
import { getAuth } from 'firebase-admin/auth';

if (!getApps().length) {
  initializeApp({
    credential: cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
    }),
  });
}

export const adminAuth = getAuth();

电子邮件/密码身份验证

注册
import { createUserWithEmailAndPassword, sendEmailVerification, updateProfile } from 'firebase/auth';
import { auth } from './firebase';

async function signUp(email: string, password: string, displayName: string) {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    const user = userCredential.user;

    // Update display name
    await updateProfile(user, { displayName });

    // Send verification email
    await sendEmailVerification(user);

    return user;
  } catch (error: any) {
    switch (error.code) {
      case 'auth/email-already-in-use':
        throw new Error('Email already registered');
      case 'auth/invalid-email':
        throw new Error('Invalid email address');
      case 'auth/weak-password':
        throw new Error('Password must be at least 6 characters');
      default:
        throw new Error('Sign up failed');
    }
  }
}
登录
import { signInWithEmailAndPassword } from 'firebase/auth';
import { auth } from './firebase';

async function signIn(email: string, password: string) {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error: any) {
    switch (error.code) {
      case 'auth/user-not-found':
      case 'auth/wrong-password':
      case 'auth/invalid-credential':
        throw new Error('Invalid email or password');
      case 'auth/user-disabled':
        throw new Error('Account has been disabled');
      case 'auth/too-many-requests':
        throw new Error('Too many attempts. Try again later.');
      default:
        throw new Error('Sign in failed');
    }
  }
}
登出
import { signOut } from 'firebase/auth';
import { auth } from './firebase';

async function handleSignOut() {
  await signOut(auth);
  // Redirect to login page
}
密码重置
import { sendPasswordResetEmail, confirmPasswordReset } from 'firebase/auth';
import { auth } from './firebase';

// Send reset email
async function resetPassword(email: string) {
  await sendPasswordResetEmail(auth, email);
}

// Confirm reset (from email link)
async function confirmReset(oobCode: string, newPassword: string) {
  await confirmPasswordReset(auth, oobCode, newPassword);
}

OAuth 提供方(Google、GitHub 等)

Google 登录
import { signInWithPopup, signInWithRedirect, GoogleAuthProvider } from 'firebase/auth';
import { auth } from './firebase';

const googleProvider = new GoogleAuthProvider();
googleProvider.addScope('email');
googleProvider.addScope('profile');

// Popup method (recommended for desktop)
async function signInWithGoogle() {
  try {
    const result = await signInWithPopup(auth, googleProvider);
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential?.accessToken;
    return result.user;
  } catch (error: any) {
    if (error.code === 'auth/popup-closed-by-user') {
      // User closed popup - not an error
      return null;
    }
    if (error.code === 'auth/popup-blocked') {
      // Fallback to redirect
      await signInWithRedirect(auth, googleProvider);
      return null;
    }
    throw error;
  }
}

// Redirect method (for mobile or popup-blocked)
async function signInWithGoogleRedirect() {
  await signInWithRedirect(auth, googleProvider);
}
处理重定向结果
import { getRedirectResult, GoogleAuthProvider } from 'firebase/auth';
import { auth } from './firebase';

// Call on page load
async function handleRedirectResult() {
  try {
    const result = await getRedirectResult(auth);
    if (result) {
      const credential = GoogleAuthProvider.credentialFromResult(result);
      return result.user;
    }
  } catch (error) {
    console.error('Redirect sign-in error:', error);
  }
  return null;
}
其他 OAuth 提供方
import {
  GithubAuthProvider,
  TwitterAuthProvider,
  FacebookAuthProvider,
  OAuthProvider,
} from 'firebase/auth';

// GitHub
const githubProvider = new GithubAuthProvider();
githubProvider.addScope('read:user');

// Microsoft
const microsoftProvider = new OAuthProvider('microsoft.com');
microsoftProvider.addScope('email');
microsoftProvider.addScope('profile');

// Apple
const appleProvider = new OAuthProvider('apple.com');
appleProvider.addScope('email');
appleProvider.addScope('name');

身份验证状态管理

监听身份验证状态变化
import { onAuthStateChanged, User } from 'firebase/auth';
import { auth } from './firebase';

// React hook example
function useAuth() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setUser(user);
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  return { user, loading };
}
身份验证上下文提供方(React)
// src/contexts/AuthContext.tsx
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { onAuthStateChanged, User } from 'firebase/auth';
import { auth } from '@/lib/firebase';

interface AuthContextType {
  user: User | null;
  loading: boolean;
}

const AuthContext = createContext<AuthContextType>({ user: null, loading: true });

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      setUser(user);
      setLoading(false);
    });

    return () => unsubscribe();
  }, []);

  return (
    <AuthContext.Provider value={{ user, loading }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);

令牌管理

获取 ID 令牌(用于 API 调用)
import { auth } from './firebase';

async function getIdToken() {
  const user = auth.currentUser;
  if (!user) throw new Error('Not authenticated');

  // Force refresh to get fresh token
  const token = await user.getIdToken(/* forceRefresh */ true);
  return token;
}

// Use in API calls
async function callProtectedAPI() {
  const token = await getIdToken();

  const response = await fetch('/api/protected', {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });

  return response.json();
}
验证 ID 令牌(服务端)
// API route (Next.js example)
import { adminAuth } from '@/lib/firebase-admin';

export async function GET(request: Request) {
  const authHeader = request.headers.get('authorization');
  if (!authHeader?.startsWith('Bearer ')) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }

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

  try {
    const decodedToken = await adminAuth.verifyIdToken(token);
    const uid = decodedToken.uid;

    // User is authenticated, proceed with request
    return Response.json({ uid, message: 'Authenticated' });
  } catch (error) {
    return Response.json({ error: 'Invalid token' }, { status: 401 });
  }
}
会话 Cookie(服务端渲染)
import { adminAuth } from '@/lib/firebase-admin';

// Create session cookie
async function createSessionCookie(idToken: string) {
  const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 days

  const sessionCookie = await adminAuth.createSessionCookie(idToken, {
    expiresIn,
  });

  return sessionCookie;
}

// Verify session cookie
async function verifySessionCookie(sessionCookie: string) {
  try {
    const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie, true);
    return decodedClaims;
  } catch (error) {
    return null;
  }
}

// Revoke session
async function revokeSession(uid: string) {
  await adminAuth.revokeRefreshTokens(uid);
}

自定义声明和角色

设置自定义声明(Admin SDK)
import { adminAuth } from '@/lib/firebase-admin';

// Set admin role
async function setAdminRole(uid: string) {
  await adminAuth.setCustomUserClaims(uid, {
    admin: true,
    role: 'admin',
  });
}

// Set custom permissions
async function setUserPermissions(uid: string, permissions: string[]) {
  await adminAuth.setCustomUserClaims(uid, {
    permissions,
  });
}
检查自定义声明(客户端)
import { auth } from './firebase';

async function checkAdminStatus() {
  const user = auth.currentUser;
  if (!user) return false;

  // Force token refresh to get latest claims
  const tokenResult = await user.getIdTokenResult(true);
  return tokenResult.claims.admin === true;
}

// In component
const isAdmin = await checkAdminStatus();

重要:自定义声明会缓存在 ID 令牌中。设置声明后,用户必须:

  1. 登出并重新登录,或
  2. 使用 getIdTokenResult(true) 强制刷新令牌

电话身份验证

import {
  signInWithPhoneNumber,
  RecaptchaVerifier,
  ConfirmationResult,
} from 'firebase/auth';
import { auth } from './firebase';

let confirmationResult: ConfirmationResult;

// Step 1: Setup reCAPTCHA (required)
function setupRecaptcha() {
  window.recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {
    size: 'normal',
    callback: () => {
      // reCAPTCHA solved
    },
  });
}

// Step 2: Send verification code
async function sendVerificationCode(phoneNumber: string) {
  const appVerifier = window.recaptchaVerifier;
  confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, appVerifier);
}

// Step 3: Verify code
async function verifyCode(code: string) {
  const result = await confirmationResult.confirm(code);
  return result.user;
}

多重身份验证(MFA)

import {
  multiFactor,
  PhoneAuthProvider,
  PhoneMultiFactorGenerator,
  getMultiFactorResolver,
} from 'firebase/auth';
import { auth } from './firebase';

// Enroll phone as second factor
async function enrollPhoneMFA(phoneNumber: string) {
  const user = auth.currentUser;
  if (!user) throw new Error('Not authenticated');

  const multiFactorSession = await multiFactor(user).getSession();

  const phoneAuthProvider = new PhoneAuthProvider(auth);
  const verificationId = await phoneAuthProvider.verifyPhoneNumber(
    { phoneNumber, session: multiFactorSession },
    window.recaptchaVerifier
  );

  // Return verificationId to complete enrollment after user enters code
  return verificationId;
}

// Complete enrollment
async function completeEnrollment(verificationId: string, verificationCode: string) {
  const user = auth.currentUser;
  if (!user) throw new Error('Not authenticated');

  const credential = PhoneAuthProvider.credential(verificationId, verificationCode);
  const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(credential);

  await multiFactor(user).enroll(multiFactorAssertion, 'Phone Number');
}

// Handle MFA during sign-in
async function handleMFASignIn(error: any) {
  if (error.code !== 'auth/multi-factor-auth-required') {
    throw error;
  }

  const resolver = getMultiFactorResolver(auth, error);
  // Show UI to select MFA method and enter code
  return resolver;
}

受保护的路由(Next.js)

中间件保护
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const sessionCookie = request.cookies.get('session')?.value;

  // Protect /dashboard routes
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    if (!sessionCookie) {
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }

  // Redirect authenticated users away from /login
  if (request.nextUrl.pathname === '/login') {
    if (sessionCookie) {
      return NextResponse.redirect(new URL('/dashboard', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/login'],
};
客户端路由守卫
// components/ProtectedRoute.tsx
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import { useEffect } from 'react';

export function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { user, loading } = useAuth();
  const router = useRouter();

  useEffect(() => {
    if (!loading && !user) {
      router.push('/login');
    }
  }, [user, loading, router]);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!user) {
    return null;
  }

  return <>{children}</>;
}

错误处理

常见身份验证错误
错误代码描述面向用户的消息
auth/invalid-credential邮箱或密码错误邮箱或密码无效
auth/user-not-found邮箱未注册邮箱或密码无效
auth/wrong-password密码错误邮箱或密码无效
auth/email-already-in-use邮箱已注册此邮箱已注册
auth/weak-password密码少于 6 个字符密码必须至少包含 6 个字符
auth/invalid-email邮箱格式错误请输入有效的邮箱
auth/user-disabled账号已停用您的账号已被停用
auth/too-many-requests请求频率受限尝试次数过多,请稍后再试
auth/popup-closed-by-user用户关闭了弹出窗口登录已取消
auth/popup-blocked浏览器阻止了弹出窗口请允许弹出窗口
auth/requires-recent-login敏感操作请重新登录
auth/network-request-failed网络错误请检查网络连接
错误处理工具
export function getAuthErrorMessage(error: any): string {
  const errorMessages: Record<string, string> = {
    'auth/invalid-credential': 'Invalid email or password',
    'auth/user-not-found': 'Invalid email or password',
    'auth/wrong-password': 'Invalid email or password',
    'auth/email-already-in-use': 'This email is already registered',
    'auth/weak-password': 'Password must be at least 6 characters',
    'auth/invalid-email': 'Please enter a valid email address',
    'auth/user-disabled': 'Your account has been disabled',
    'auth/too-many-requests': 'Too many attempts. Please try again later',
    'auth/popup-closed-by-user': 'Sign-in was cancelled',
    'auth/network-request-failed': 'Network error. Please check your connection',
  };

  return errorMessages[error.code] || 'An unexpected error occurred';
}

已知问题防范

此技能可防范 12 个有记录的 Firebase Auth 错误:

问题编号错误/问题描述如何避免来源
#1auth/invalid-credential输入错误的邮箱/密码时出现的通用错误显示通用的“邮箱或密码无效”消息常见
#2auth/popup-blocked浏览器阻止 OAuth 弹出窗口实现重定向回退方案文档
#3auth/requires-recent-login敏感操作需要近期登录更改密码或删除账户前重新进行身份验证文档
#4自定义声明未更新声明缓存在 ID 令牌中设置声明后强制刷新令牌文档
#5令牌过期ID 令牌在 1 小时后过期调用 API 前始终调用 getIdToken()常见
#6身份验证监听器导致内存泄漏未取消订阅 onAuthStateChanged在 useEffect 中返回清理函数常见
#7localhost 上出现 CORS 错误身份验证域不匹配在控制台中将 localhost 添加到授权域常见
#8私钥换行符问题环境变量中的 \n 被转义使用 .replace(/\\n/g, '\n')常见
#9会话 Cookie 未持久化Cookie 设置错误在生产环境中设置 secure: true、sameSite: 'lax'常见
#10OAuth 状态不匹配用户在 OAuth 过程中离开页面妥善处理 auth/popup-closed-by-user常见
#11速率限制身份验证尝试次数过多实现指数退避文档
#12邮箱枚举对已存在和不存在的邮箱返回不同错误两种情况使用相同的消息安全最佳实践

安全最佳实践

始终执行
  1. 在生产环境中使用 HTTPS - 安全 Cookie 的必要条件
  2. 在服务器端验证令牌 - 绝不单独信任客户端声明
  3. 处理令牌过期 - 调用 API 前刷新令牌
  4. 实施速率限制 - 防止暴力攻击
  5. 对错误的邮箱/密码使用相同的错误消息 - 防止邮箱枚举
  6. 启用邮箱验证 - 验证用户拥有该邮箱
  7. 对 SSR 使用会话 Cookie - 比将 ID 令牌存储在 Cookie 中更安全
  8. 更改密码时撤销令牌 - 使旧会话失效
绝不执行
  1. 绝不在客户端代码中暴露私钥
  2. 绝不信任客户端提供的声明 - 始终在服务器端验证
  3. 绝不将 ID 令牌存储在 localStorage 中 - 使用 httpOnly Cookie
  4. 绝不在生产环境中禁用邮箱枚举保护
  5. 绝不跳过针对你域名的 CORS 配置

Firebase CLI 命令

# Initialize Firebase project
firebase init

# Enable auth emulator
firebase emulators:start --only auth

# Export auth users
firebase auth:export users.json --format=json

# Import auth users
firebase auth:import users.json

软件包版本(已于 2026-01-25 验证)

{
  "dependencies": {
    "firebase": "^12.8.0"
  },
  "devDependencies": {
    "firebase-admin": "^13.6.0"
  }
}

官方文档


上次验证时间:2026-01-25 | 技能版本:1.0.0

评论

支持 Markdown