firebase-auth by jezweb/claude-skills
npx skills add https://github.com/jezweb/claude-skills --skill firebase-auth状态 : 生产就绪 最后更新 : 2026-01-25 依赖项 : 无(独立技能) 最新版本 : firebase@12.8.0, firebase-admin@13.6.0
// 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);
// 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();
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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;
// 更新显示名称
await updateProfile(user, { displayName });
// 发送验证邮件
await sendEmailVerification(user);
return user;
} catch (error: any) {
switch (error.code) {
case 'auth/email-already-in-use':
throw new Error('该邮箱已被注册');
case 'auth/invalid-email':
throw new Error('无效的邮箱地址');
case 'auth/weak-password':
throw new Error('密码长度必须至少为6个字符');
default:
throw new Error('注册失败');
}
}
}
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('邮箱或密码错误');
case 'auth/user-disabled':
throw new Error('账户已被禁用');
case 'auth/too-many-requests':
throw new Error('尝试次数过多,请稍后再试');
default:
throw new Error('登录失败');
}
}
}
import { signOut } from 'firebase/auth';
import { auth } from './firebase';
async function handleSignOut() {
await signOut(auth);
// 重定向到登录页面
}
import { sendPasswordResetEmail, confirmPasswordReset } from 'firebase/auth';
import { auth } from './firebase';
// 发送重置邮件
async function resetPassword(email: string) {
await sendPasswordResetEmail(auth, email);
}
// 确认重置(从邮件链接)
async function confirmReset(oobCode: string, newPassword: string) {
await confirmPasswordReset(auth, oobCode, newPassword);
}
import { signInWithPopup, signInWithRedirect, GoogleAuthProvider } from 'firebase/auth';
import { auth } from './firebase';
const googleProvider = new GoogleAuthProvider();
googleProvider.addScope('email');
googleProvider.addScope('profile');
// 弹窗方法(推荐用于桌面端)
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') {
// 用户关闭了弹窗 - 不是错误
return null;
}
if (error.code === 'auth/popup-blocked') {
// 回退到重定向方式
await signInWithRedirect(auth, googleProvider);
return null;
}
throw error;
}
}
// 重定向方法(用于移动端或弹窗被阻止时)
async function signInWithGoogleRedirect() {
await signInWithRedirect(auth, googleProvider);
}
import { getRedirectResult, GoogleAuthProvider } from 'firebase/auth';
import { auth } from './firebase';
// 在页面加载时调用
async function handleRedirectResult() {
try {
const result = await getRedirectResult(auth);
if (result) {
const credential = GoogleAuthProvider.credentialFromResult(result);
return result.user;
}
} catch (error) {
console.error('重定向登录错误:', error);
}
return null;
}
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 示例
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 };
}
// 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);
import { auth } from './firebase';
async function getIdToken() {
const user = auth.currentUser;
if (!user) throw new Error('未认证');
// 强制刷新以获取新令牌
const token = await user.getIdToken(/* forceRefresh */ true);
return token;
}
// 在 API 调用中使用
async function callProtectedAPI() {
const token = await getIdToken();
const response = await fetch('/api/protected', {
headers: {
Authorization: `Bearer ${token}`,
},
});
return response.json();
}
// API 路由(Next.js 示例)
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: '未授权' }, { status: 401 });
}
const token = authHeader.split('Bearer ')[1];
try {
const decodedToken = await adminAuth.verifyIdToken(token);
const uid = decodedToken.uid;
// 用户已认证,继续处理请求
return Response.json({ uid, message: '已认证' });
} catch (error) {
return Response.json({ error: '无效令牌' }, { status: 401 });
}
}
import { adminAuth } from '@/lib/firebase-admin';
// 创建会话 Cookie
async function createSessionCookie(idToken: string) {
const expiresIn = 60 * 60 * 24 * 5 * 1000; // 5 天
const sessionCookie = await adminAuth.createSessionCookie(idToken, {
expiresIn,
});
return sessionCookie;
}
// 验证会话 Cookie
async function verifySessionCookie(sessionCookie: string) {
try {
const decodedClaims = await adminAuth.verifySessionCookie(sessionCookie, true);
return decodedClaims;
} catch (error) {
return null;
}
}
// 撤销会话
async function revokeSession(uid: string) {
await adminAuth.revokeRefreshTokens(uid);
}
import { adminAuth } from '@/lib/firebase-admin';
// 设置管理员角色
async function setAdminRole(uid: string) {
await adminAuth.setCustomUserClaims(uid, {
admin: true,
role: 'admin',
});
}
// 设置自定义权限
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;
// 强制刷新令牌以获取最新声明
const tokenResult = await user.getIdTokenResult(true);
return tokenResult.claims.admin === true;
}
// 在组件中
const isAdmin = await checkAdminStatus();
重要提示: 自定义声明会缓存在 ID 令牌中。设置声明后,用户必须:
getIdTokenResult(true) 强制刷新令牌import {
signInWithPhoneNumber,
RecaptchaVerifier,
ConfirmationResult,
} from 'firebase/auth';
import { auth } from './firebase';
let confirmationResult: ConfirmationResult;
// 步骤 1:设置 reCAPTCHA(必需)
function setupRecaptcha() {
window.recaptchaVerifier = new RecaptchaVerifier(auth, 'recaptcha-container', {
size: 'normal',
callback: () => {
// reCAPTCHA 已解决
},
});
}
// 步骤 2:发送验证码
async function sendVerificationCode(phoneNumber: string) {
const appVerifier = window.recaptchaVerifier;
confirmationResult = await signInWithPhoneNumber(auth, phoneNumber, appVerifier);
}
// 步骤 3:验证代码
async function verifyCode(code: string) {
const result = await confirmationResult.confirm(code);
return result.user;
}
import {
multiFactor,
PhoneAuthProvider,
PhoneMultiFactorGenerator,
getMultiFactorResolver,
} from 'firebase/auth';
import { auth } from './firebase';
// 注册手机作为第二因素
async function enrollPhoneMFA(phoneNumber: string) {
const user = auth.currentUser;
if (!user) throw new Error('未认证');
const multiFactorSession = await multiFactor(user).getSession();
const phoneAuthProvider = new PhoneAuthProvider(auth);
const verificationId = await phoneAuthProvider.verifyPhoneNumber(
{ phoneNumber, session: multiFactorSession },
window.recaptchaVerifier
);
// 返回 verificationId,以便用户在输入代码后完成注册
return verificationId;
}
// 完成注册
async function completeEnrollment(verificationId: string, verificationCode: string) {
const user = auth.currentUser;
if (!user) throw new Error('未认证');
const credential = PhoneAuthProvider.credential(verificationId, verificationCode);
const multiFactorAssertion = PhoneMultiFactorGenerator.assertion(credential);
await multiFactor(user).enroll(multiFactorAssertion, 'Phone Number');
}
// 在登录期间处理 MFA
async function handleMFASignIn(error: any) {
if (error.code !== 'auth/multi-factor-auth-required') {
throw error;
}
const resolver = getMultiFactorResolver(auth, error);
// 显示 UI 以选择 MFA 方法并输入代码
return resolver;
}
// 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;
// 保护 /dashboard 路由
if (request.nextUrl.pathname.startsWith('/dashboard')) {
if (!sessionCookie) {
return NextResponse.redirect(new URL('/login', request.url));
}
}
// 将已认证用户从 /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>加载中...</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': '邮箱或密码错误',
'auth/user-not-found': '邮箱或密码错误',
'auth/wrong-password': '邮箱或密码错误',
'auth/email-already-in-use': '该邮箱已被注册',
'auth/weak-password': '密码长度必须至少为6个字符',
'auth/invalid-email': '请输入有效的邮箱地址',
'auth/user-disabled': '您的账户已被禁用',
'auth/too-many-requests': '尝试次数过多,请稍后再试',
'auth/popup-closed-by-user': '登录已取消',
'auth/network-request-failed': '网络错误,请检查您的连接',
};
return errorMessages[error.code] || '发生意外错误';
}
此技能预防了 12 个已记录的 Firebase Auth 错误:
| 问题编号 | 错误/问题 | 描述 | 如何避免 | 来源 |
|---|---|---|---|---|
| #1 | auth/invalid-credential | 错误的邮箱/密码的通用错误 | 显示通用的"邮箱或密码错误"消息 | 常见 |
| #2 | auth/popup-blocked | 浏览器阻止 OAuth 弹窗 | 实现重定向回退 | 文档 |
| #3 | auth/requires-recent-login | 敏感操作需要重新登录 | 在更改密码、删除前重新认证 | 文档 |
| #4 | 自定义声明未更新 | 声明缓存在 ID 令牌中 | 设置声明后强制刷新令牌 | 文档 |
| #5 | 令牌过期 | ID 令牌在1小时后过期 | 在 API 调用前始终调用 getIdToken() | 常见 |
| #6 | 认证监听器内存泄漏 | 未取消订阅 onAuthStateChanged | 在 useEffect 中返回清理函数 | 常见 |
| #7 | localhost 上的 CORS 错误 | 认证域名不匹配 | 在控制台中将 localhost 添加到授权域名 | 常见 |
| #8 | 私钥换行符问题 | 环境变量中的转义 \n | 使用 .replace(/\\n/g, '\n') | 常见 |
| #9 | 会话 Cookie 未持久化 | Cookie 设置错误 | 在生产环境中设置 secure: true, sameSite: 'lax' | 常见 |
| #10 | OAuth 状态不匹配 | 用户在 OAuth 过程中离开页面 | 优雅处理 auth/popup-closed-by-user | 常见 |
| #11 | 频率限制 | 认证尝试次数过多 | 实现指数退避 | 文档 |
| #12 | 邮箱枚举 | 对存在/不存在的邮箱显示不同错误 | 对两者使用相同的消息 | 安全最佳实践 |
# 初始化 Firebase 项目
firebase init
# 启用认证模拟器
firebase emulators:start --only auth
# 导出认证用户
firebase auth:export users.json --format=json
# 导入认证用户
firebase auth:import users.json
{
"dependencies": {
"firebase": "^12.8.0"
},
"devDependencies": {
"firebase-admin": "^13.6.0"
}
}
最后验证 : 2026-01-25 | 技能版本 : 1.0.0
每周安装数
363
代码仓库
GitHub 星标数
643
首次出现
2026年1月26日
安全审计
已安装于
claude-code277
gemini-cli250
opencode248
codex220
antigravity214
cursor206
Status : Production Ready Last Updated : 2026-01-25 Dependencies : None (standalone skill) Latest Versions : firebase@12.8.0, firebase-admin@13.6.0
// 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);
// 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);
}
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;
}
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 };
}
// 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);
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();
}
// 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 });
}
}
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);
}
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();
CRITICAL: Custom claims are cached in the ID token. After setting claims, the user must:
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;
}
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;
}
// 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}</>;
}
| Error Code | Description | User-Friendly Message |
|---|---|---|
auth/invalid-credential | Wrong email/password | Invalid email or password |
auth/user-not-found | Email not registered | Invalid email or password |
auth/wrong-password | Incorrect password | Invalid email or password |
auth/email-already-in-use | Email registered | This email is already registered |
auth/weak-password |
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';
}
This skill prevents 12 documented Firebase Auth errors:
| Issue # | Error/Issue | Description | How to Avoid | Source |
|---|---|---|---|---|
| #1 | auth/invalid-credential | Generic error for wrong email/password | Show generic "invalid email or password" message | Common |
| #2 | auth/popup-blocked | Browser blocks OAuth popup | Implement redirect fallback | Docs |
| #3 | auth/requires-recent-login | Sensitive operations need fresh login |
# 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
{
"dependencies": {
"firebase": "^12.8.0"
},
"devDependencies": {
"firebase-admin": "^13.6.0"
}
}
Last verified : 2026-01-25 | Skill version : 1.0.0
Weekly Installs
363
Repository
GitHub Stars
643
First Seen
Jan 26, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code277
gemini-cli250
opencode248
codex220
antigravity214
cursor206
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装
| Password < 6 chars |
| Password must be at least 6 characters |
auth/invalid-email | Malformed email | Please enter a valid email |
auth/user-disabled | Account disabled | Your account has been disabled |
auth/too-many-requests | Rate limited | Too many attempts. Try again later |
auth/popup-closed-by-user | User closed popup | Sign-in cancelled |
auth/popup-blocked | Browser blocked popup | Please allow popups |
auth/requires-recent-login | Sensitive operation | Please sign in again |
auth/network-request-failed | Network error | Please check your connection |
| Re-authenticate before password change, delete |
| Docs |
| #4 | Custom claims not updating | Claims cached in ID token | Force token refresh after setting claims | Docs |
| #5 | Token expiration | ID tokens expire after 1 hour | Always call getIdToken() before API calls | Common |
| #6 | Memory leak from auth listener | Not unsubscribing from onAuthStateChanged | Return cleanup function in useEffect | Common |
| #7 | CORS errors on localhost | Auth domain mismatch | Add localhost to authorized domains in console | Common |
| #8 | Private key newline issue | Escaped \n in env var | Use .replace(/\\n/g, '\n') | Common |
| #9 | Session cookie not persisting | Cookie settings wrong | Set secure: true, sameSite: 'lax' in production | Common |
| #10 | OAuth state mismatch | User navigates away during OAuth | Handle auth/popup-closed-by-user gracefully | Common |
| #11 | Rate limiting | Too many auth attempts | Implement exponential backoff | Docs |
| #12 | Email enumeration | Different errors for existing/non-existing emails | Use same message for both | Security best practice |