关于 modern-auth-2026
面向构建 Web 和移动应用的开发者,提供无密码认证实践指南,涵盖 Passkey、OAuth、恢复流程和 Supabase Auth 配置,并附实现示例与故障排查。
主要功能
- 01Passkey 与 WebAuthn 实现指南
- 02Google 和 Apple OAuth 配置
- 03Magic Link 与 OTP 流程
- 04MFA 与账户恢复方案
- 05Supabase Auth 配置及排障
适用场景
- 01为 Web 应用添加 Passkey 登录
- 02配置 Supabase Auth 社交登录
- 03设计电子邮件或短信账户恢复流程
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ curiositech/ some_claude_skills --skill modern-auth-2026安装后在 Claude Code 中输入/modern-auth-2026确认已加载。
附带文件.claude-plugin/plugin.json
详细介绍
现代身份验证专家(2026)
为现代 Web 和移动应用掌握以无密码为先的身份验证,包括通行密钥、OAuth、魔法链接和跨设备同步。
适用场景
✅ 在以下场景使用此技能:
- 实现通行密钥/WebAuthn 身份验证
- Google 和 Apple OAuth 社交登录
- 配置和排查 Supabase Auth
- 魔法链接/OTP 无密码流程
- 跨设备身份验证同步
- 实现 MFA(TOTP、将通行密钥用作 2FA)
- 电子邮件/SMS 恢复流程
- 社交登录的 App Store 合规要求
❌ 在以下场景不要使用:
- 不涉及身份验证的会话管理 → 使用标准 JWT 模式
- 授权/RBAC 策略 → 使用
security-auditor技能 - API 密钥管理 → 使用
api-architect技能 - Supabase RLS 策略 → 使用
supabase-admin技能
2026 年身份验证概况
行业采用率统计
- 通行密钥: 美国/英国 87% 的公司现在使用通行密钥(FIDO Alliance)
- Google: 超过 8 亿个账户使用通行密钥
- Amazon: 首年有 1.75 亿用户创建了通行密钥
- 趋势: 无密码已成为安全基线,而非奢侈选项
关键标准
| 标准 | 用途 | 状态 |
|---|---|---|
| WebAuthn L2 | 浏览器通行密钥 API | 已全面支持 |
| FIDO2/CTAP2 | 跨平台通行密钥 | 已成熟 |
| OAuth 2.1 | 简化版 OAuth | 正在取代 2.0 |
| OAuth3 | 短时效令牌 | 新兴 |
| 通行密钥同步 | iCloud/Google 同步 | 已投入生产 |
架构:以无密码为先的设计
推荐的身份验证层级(2026)
Primary Methods (Phishing-Resistant):
├── 1. Passkeys (WebAuthn) ← PREFERRED
│ ├── Platform authenticators (Face ID, Touch ID, Windows Hello)
│ └── Roaming authenticators (YubiKey, security keys)
├── 2. Social OAuth
│ ├── Google Sign-In (synced passkeys)
│ └── Apple Sign-In (privacy-focused)
│
Fallback Methods (Lower Security):
├── 3. Magic Links (email-based)
├── 4. Email OTP (time-limited codes)
└── 5. SMS OTP (deprecated - SIM swap risk)
⚠️ SMS should be last resort only
Legacy (Avoid):
└── 6. Password + Email ← DISCOURAGE
安全等级对比
| 方式 | 抗钓鱼 | 绑定设备 | 支持同步 | 使用门槛 |
|---|---|---|---|---|
| 通行密钥 | ✅ 是 | ✅ 是 | ✅ 是 | 低 |
| 硬件密钥 | ✅ 是 | ✅ 是 | ❌ 否 | 中 |
| Google OAuth | ⚠️ 部分支持 | ❌ 否 | ✅ 是 | 低 |
| Apple OAuth | ⚠️ 部分支持 | ❌ 否 | ✅ 是 | 低 |
| 魔法链接 | ❌ 否 | ❌ 否 | ✅ 是 | 中 |
| 电子邮件 OTP | ❌ 否 | ❌ 否 | ✅ 是 | 中 |
| SMS OTP | ❌ 否 | ❌ 否 | ❌ 否 | 中 |
| 密码 | ❌ 否 | ❌ 否 | ✅ 是 | 低 |
通行密钥(WebAuthn)实现
通行密钥的工作原理
Registration Flow:
┌──────────┐ ┌──────────┐ ┌──────────┐
│ User │─────▶│ Browser │─────▶│ Server │
│ │ │ WebAuthn │ │ │
└──────────┘ └──────────┘ └──────────┘
│ │ │
│ 1. User clicks │ │
│ "Register" │ │
│ │ 2. Server sends │
│ │◀─ challenge + │
│ │ user info │
│ 3. Device shows │ │
│◀─ biometric │ │
│ │ │
│ 4. User │ │
│─▶ authenticates │ │
│ │ 5. Send public │
│ │─▶ key + signed │
│ │ challenge │
│ │ │
│ │ 6. Server stores│
│ │◀─ public key │
└──────────────────┴──────────────────┘
Key Points:
- Private key NEVER leaves device
- Server only stores public key
- Biometric data stays local
- Credential bound to domain (anti-phishing)
库推荐
前端:
{
"@simplewebauthn/browser": "^10.0.0",
"next-passkey-webauthn": "^2.0.0"
}
后端:
{
"@simplewebauthn/server": "^10.0.0"
}
Next.js 通行密钥实现
1. 数据库架构(Supabase):
-- Store passkey credentials
CREATE TABLE passkey_credentials (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid REFERENCES auth.users(id) ON DELETE CASCADE,
credential_id text UNIQUE NOT NULL,
public_key bytea NOT NULL,
counter integer DEFAULT 0,
transports text[], -- e.g., ['internal', 'hybrid']
device_type text, -- 'platform' or 'cross-platform'
backed_up boolean DEFAULT false,
created_at timestamptz DEFAULT now(),
last_used_at timestamptz
);
CREATE INDEX idx_passkey_user_id ON passkey_credentials(user_id);
CREATE INDEX idx_passkey_credential_id ON passkey_credentials(credential_id);
-- RLS policies
ALTER TABLE passkey_credentials ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users can read own credentials" ON passkey_credentials
FOR SELECT USING (auth.uid() = user_id);
CREATE POLICY "Users can insert own credentials" ON passkey_credentials
FOR INSERT WITH CHECK (auth.uid() = user_id);
CREATE POLICY "Users can delete own credentials" ON passkey_credentials
FOR DELETE USING (auth.uid() = user_id);
2. 注册 API 路由(app/api/passkeys/register/route.ts):
import { generateRegistrationOptions, verifyRegistrationResponse } from '@simplewebauthn/server';
import { createClient } from '@/lib/supabase/server';
const RP_NAME = 'Your App Name';
const RP_ID = process.env.NODE_ENV === 'production'
? 'yourapp.com'
: 'localhost';
export async function POST(request: Request) {
const supabase = createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) {
return Response.json({ error: 'Unauthorized' }, { status: 401 });
}
const { step, credential } = await request.json();
if (step === 'options') {
// Get existing credentials to exclude
const { data: existingCreds } = await supabase
.from('passkey_credentials')
.select('credential_id')
.eq('user_id', user.id);
const options = await generateRegistrationOptions({
rpName: RP_NAME,
rpID: RP_ID,
userID: user.id,
userName: user.email!,
userDisplayName: user.user_metadata?.display_name || user.email!,
attestationType: 'none', // For privacy
excludeCredentials: existingCreds?.map(c => ({
id: Buffer.from(c.credential_id, 'base64url'),
type: 'public-key',
})) || [],
authenticatorSelection: {
residentKey: 'preferred', // Discoverable credentials
userVerification: 'preferred', // Biometric when available
authenticatorAttachment: 'platform', // Device-bound (not roaming keys)
},
});
// Store challenge in session (or use signed JWT)
await supabase.from('auth_challenges').upsert({
user_id: user.id,
challenge: options.challenge,
expires_at: new Date(Date.now() + 5 * 60 * 1000), // 5 min
});
return Response.json(options);
}
if (step === 'verify') {
// Get stored challenge
const { data: challengeData } = await supabase
.from('auth_challenges')
.select('challenge')
.eq('user_id', user.id)
.single();
const verification = await verifyRegistrationResponse({
response: credential,
expectedChallenge: challengeData!.challenge,
expectedOrigin: process.env.NEXT_PUBLIC_APP_URL!,
expectedRPID: RP_ID,
});
if (verification.verified && verification.registrationInfo) {
const { credentialID, credentialPublicKey, counter } = verification.registrationInfo;
await supabase.from('passkey_credentials').insert({
user_id: user.id,
credential_id: Buffer.from(credentialID).toString('base64url'),
public_key: Buffer.from(credentialPublicKey),
counter,
transports: credential.response.transports,
device_type: verification.registrationInfo.credentialDeviceType,
backed_up: verification.registrationInfo.credentialBackedUp,
});
return Response.json({ success: true });
}
return Response.json({ error: 'Verification failed' }, { status: 400 });
}
}
3. 身份验证 API 路由(app/api/passkeys/authenticate/route.ts):
import { generateAuthenticationOptions, verifyAuthenticationResponse } from '@simplewebauthn/server';
import { createClient } from '@/lib/supabase/server';
export async function POST(request: Request) {
const supabase = createClient();
const { step, credential, email } = await request.json();
if (step === 'options') {
// For discoverable credentials, email is optional
let userCredentials = [];
if (email) {
const { data: user } = await supabase
.from('profiles')
.select('id')
.eq('email', email)
.single();
if (user) {
const { data: creds } = await supabase
.from('passkey_credentials')
.select('credential_id, transports')
.eq('user_id', user.id);
userCredentials = creds || [];
}
}
const options = await generateAuthenticationOptions({
rpID: RP_ID,
userVerification: 'preferred',
allowCredentials: userCredentials.length ? userCredentials.map(c => ({
id: Buffer.from(c.credential_id, 'base64url'),
type: 'public-key',
transports: c.transports,
})) : undefined, // Empty = discoverable credential flow
});
// Store challenge
await supabase.from('auth_challenges').upsert({
challenge_id: options.challenge,
challenge: options.challenge,
expires_at: new Date(Date.now() + 5 * 60 * 1000),
});
return Response.json(options);
}
if (step === 'verify') {
// Find credential
const credentialId = Buffer.from(credential.id, 'base64url').toString('base64url');
const { data: storedCred } = await supabase
.from('passkey_credentials')
.select('*, profiles!inner(email)')
.eq('credential_id', credentialId)
.single();
if (!storedCred) {
return Response.json({ error: 'Credential not found' }, { status: 401 });
}
// Get challenge
const { data: challengeData } = await supabase
.from('auth_challenges')
.select('challenge')
.eq('challenge_id', credential.response.clientDataJSON.challenge)
.single();
const verification = await verifyAuthenticationResponse({
response: credential,
expectedChallenge: challengeData!.challenge,
expectedOrigin: process.env.NEXT_PUBLIC_APP_URL!,
expectedRPID: RP_ID,
authenticator: {
credentialID: Buffer.from(storedCred.credential_id, 'base64url'),
credentialPublicKey: storedCred.public_key,
counter: storedCred.counter,
},
});
if (verification.verified) {
// Update counter
await supabase
.from('passkey_credentials')
.update({
counter: verification.authenticationInfo.newCounter,
last_used_at: new Date(),
})
.eq('id', storedCred.id);
// Create Supabase session
const { data: session } = await supabase.auth.admin.generateLink({
type: 'magiclink',
email: storedCred.profiles.email,
});
return Response.json({
success: true,
session: session.properties?.hashed_token
});
}
return Response.json({ error: 'Verification failed' }, { status: 401 });
}
}
4. 前端 Hook(hooks/usePasskey.ts):
import { startRegistration, startAuthentication } from '@simplewebauthn/browser';
import { useState } from 'react';
export function usePasskey() {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const registerPasskey = async () => {
setIsLoading(true);
setError(null);
try {
// Get options from server
const optionsRes = await fetch('/api/passkeys/register', {
method: 'POST',
body: JSON.stringify({ step: 'options' }),
});
const options = await optionsRes.json();
// Start WebAuthn registration
const credential = await startRegistration(options);
// Verify with server
const verifyRes = await fetch('/api/passkeys/register', {
method: 'POST',
body: JSON.stringify({ step: 'verify', credential }),
});
if (!verifyRes.ok) {
throw new Error('Verification failed');
}
return true;
} catch (err: any) {
// Handle user cancellation gracefully
if (err.name === 'NotAllowedError') {
setError('Passkey registration cancelled');
} else {
setError(err.message);
}
return false;
} finally {
setIsLoading(false);
}
};
const authenticateWithPasskey = async (email?: string) => {
setIsLoading(true);
setError(null);
try {
const optionsRes = await fetch('/api/passkeys/authenticate', {
method: 'POST',
body: JSON.stringify({ step: 'options', email }),
});
const options = await optionsRes.json();
const credential = await startAuthentication(options);
const verifyRes = await fetch('/api/passkeys/authenticate', {
method: 'POST',
body: JSON.stringify({ step: 'verify', credential }),
});
if (!verifyRes.ok) {
throw new Error('Authentication failed');
}
const { session } = await verifyRes.json();
// Exchange for Supabase session
// ...
return true;
} catch (err: any) {
if (err.name === 'NotAllowedError') {
setError('Passkey authentication cancelled');
} else {
setError(err.message);
}
return false;
} finally {
setIsLoading(false);
}
};
const isSupported = typeof window !== 'undefined' &&
window.PublicKeyCredential !== undefined;
return {
registerPasskey,
authenticateWithPasskey,
isSupported,
isLoading,
error,
};
}
OAuth:Google 登录
设置要求
-
Google Cloud Console:
- 创建 OAuth 2.0 Client ID(Web 应用)
- 添加授权的 JavaScript 源:
https://yourapp.com - 添加授权的重定向 URI:
https://yourapp.supabase.co/auth/v1/callback
-
Supabase Dashboard:
- Authentication → Providers → Google
- 添加 Client ID 和 Client Secret
- 启用“Sign in with Google”
实现
Supabase 客户端(Next.js):
import { createClient } from '@/lib/supabase/client';
async function signInWithGoogle() {
const supabase = createClient();
const { error } = await supabase.auth.signInWithOAuth({
provider: 'google',
options: {
redirectTo: `${window.location.origin}/auth/callback`,
queryParams: {
access_type: 'offline', // For refresh tokens
prompt: 'consent', // Force consent screen
},
},
});
if (error) {
console.error('Google sign-in error:', error);
}
}
原生移动端(React Native/Expo):
import * as Google from 'expo-auth-session/providers/google';
import { createClient } from '@supabase/supabase-js';
export function useGoogleAuth() {
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: process.env.EXPO_PUBLIC_GOOGLE_CLIENT_ID,
iosClientId: process.env.EXPO_PUBLIC_GOOGLE_IOS_CLIENT_ID,
androidClientId: process.env.EXPO_PUBLIC_GOOGLE_ANDROID_CLIENT_ID,
});
useEffect(() => {
if (response?.type === 'success') {
const { id_token } = response.params;
supabase.auth.signInWithIdToken({
provider: 'google',
token: id_token,
});
}
}, [response]);
return { signIn: () => promptAsync(), isLoading: !request };
}
OAuth:Apple 登录
App Store 要求(2024 年及以后)
⚠️ 关键合规规则:
使用第三方登录(Google、Facebook 等)的应用还必须提供同等的隐私保护选项。通过 Apple 登录可满足此要求。
提供以下登录方式时必须提供: Google、Facebook、Twitter、Amazon、WeChat 例外情况: 使用现有 SSO 的企业/教育类应用
设置要求
-
Apple Developer Portal:
- 启用“Sign in with Apple”功能
- 为 Web 创建 Service ID
- 创建用于生成令牌的密钥(.p8 文件)
- ⚠️ 密钥每 6 个月过期——设置日历提醒!
-
Supabase Dashboard:
- Authentication → Providers → Apple
- 添加 Service ID、Team ID、Key ID
- 上传 .p8 密钥文件
实现
Web(Supabase):
async function signInWithApple() {
const supabase = createClient();
const { error } = await supabase.auth.signInWithOAuth({
provider: 'apple',
options: {
redirectTo: `${window.location.origin}/auth/callback`,
},
});
if (error) {
console.error('Apple sign-in error:', error);
}
}
原生 iOS(Swift):
import AuthenticationServices
func handleAppleSignIn() async throws {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let result = try await performSignIn(request)
// Extract ID token
guard let identityToken = result.credential.identityToken,
let tokenString = String(data: identityToken, encoding: .utf8) else {
throw AuthError.missingToken
}
// Sign in to Supabase
try await supabase.auth.signInWithIdToken(
credentials: .init(
provider: .apple,
idToken: tokenString
)
)
}
魔法链接(电子邮件无密码登录)
最佳实践
// ✅ Good: Short TTL, single-use
const { error } = await supabase.auth.signInWithOtp({
email: user.email,
options: {
emailRedirectTo: `${origin}/auth/callback`,
shouldCreateUser: true, // Auto-create on first login
},
});
// Configure in Supabase Dashboard:
// - Magic Link expiry: 5-10 minutes (shorter is safer)
// - Rate limit: 3 per hour per email
电子邮件模板自定义
<h2>Sign in to {{ .SiteURL }}</h2>
<p>Click the link below to sign in. This link expires in 10 minutes.</p>
<p><a href="{{ .ConfirmationURL }}">Sign in to Your Account</a></p>
<p>If you didn't request this, you can safely ignore this email.</p>
恢复流程
电子邮件恢复(重置密码)
// Request reset
await supabase.auth.resetPasswordForEmail(email, {
redirectTo: `${origin}/auth/update-password`,
});
// Update password (on /auth/update-password page)
await supabase.auth.updateUser({ password: newPassword });
账户恢复层级
Recovery Options (in order of security):
1. Backup Passkey (stored on different device)
2. Trusted Recovery Contact (delegated access)
3. Email verification + Security questions
4. Email-only recovery (last resort)
5. SMS recovery ⚠️ (vulnerable to SIM swap)
实施备用通行密钥
// Prompt user to register backup device after primary
function PromptBackupPasskey() {
const [hasBackup, setHasBackup] = useState(false);
const { data: credentials } = usePasskeyCredentials();
useEffect(() => {
// Check if user has only one passkey
if (credentials?.length === 1) {
setHasBackup(false);
}
}, [credentials]);
if (hasBackup) return null;
return (
<div className="bg-amber-50 border border-amber-200 p-4 rounded-lg">
<h3>Add a Backup Passkey</h3>
<p>Register a passkey on another device to ensure account recovery.</p>
<Button onClick={registerPasskey}>Add Backup Device</Button>
</div>
);
}
跨设备同步
通行密钥同步方式
Device A (iPhone) iCloud Keychain Device B (Mac)
┌─────────────────┐ ┌─────────────┐ ┌─────────────────┐
│ Create Passkey │──────────▶│ E2E Encrypt │──────────▶│ Passkey Ready │
│ for example.com │ │ & Sync │ │ to use │
└─────────────────┘ └─────────────┘ └─────────────────┘
Google Password Manager:
- Android devices synced
- Chrome browser synced
- Windows via Chrome
Apple iCloud Keychain:
- All Apple devices synced
- Safari on all platforms
- Shared with Family Sharing (optional)
跨平台身份验证(二维码)
当用户想在没有通行密钥的设备上登录时:
// Device A shows QR code
// User scans with phone (Device B) that has passkey
// Phone authenticates via Bluetooth proximity
// This is handled automatically by the browser's WebAuthn implementation
// No additional code needed - just allow hybrid transports:
const options = await generateAuthenticationOptions({
rpID: RP_ID,
authenticatorSelection: {
// Allow cross-device (QR code) authentication
authenticatorAttachment: undefined, // Don't restrict
},
});
Supabase Auth 配置检查清单
控制台设置
-
Authentication → Settings:
- Site URL:
https://yourapp.com - Redirect URLs:添加所有有效的回调地址
- JWT Expiry:3600(1 小时)
- 启用电子邮件确认:是
- Site URL:
-
Authentication → Providers → Email:
- 启用 Email:是
- 确认电子邮件:是(推荐)
- 安全地更改电子邮件:是
- 双重确认电子邮件:否(减少操作阻碍)
-
Authentication → Email Templates:
- 自定义所有模板
- 测试电子邮件送达情况
- 设置适当的过期时间
-
Authentication → Rate Limiting:
- 电子邮件:每小时 3 次
- SMS:每小时 3 次
- 魔法链接:每 5 分钟 3 次
环境变量
# Required
NEXT_PUBLIC_SUPABASE_URL=https://yourproject.supabase.co
NEXT_PUBLIC_SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_ROLE_KEY=your-service-key
# Google OAuth
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret
# Apple OAuth
APPLE_SERVICE_ID=your-service-id
APPLE_TEAM_ID=your-team-id
APPLE_KEY_ID=your-key-id
APPLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n..."
# Passkeys
PASSKEY_RP_ID=yourapp.com
PASSKEY_RP_NAME="Your App Name"
常见问题与解决方案
问题:注册时显示“检查电子邮件”,但没有收到邮件
原因: 未在 Supabase 控制台中配置电子邮件确认
解决方案:
- 前往 Supabase 控制台 → Authentication → Providers → Email
- 确认已启用“Confirm email”
- 检查是否已配置电子邮件模板
- 确认 SMTP 设置(或使用 Supabase 内置的电子邮件功能)
- 检查垃圾邮件文件夹
问题:Apple Sign-In 突然停止工作
原因: Apple .p8 密钥已过期(有效期为 6 个月)
解决方案:
- 在 Apple Developer Portal 中生成新密钥
- 在 Supabase 控制台中更新密钥
- 为下次过期设置日历提醒
问题:Google OAuth 重定向错误
原因: 重定向 URI 不匹配
解决方案:
- 确认 Google Cloud Console 中的重定向 URI 完全一致:
https://yourproject.supabase.co/auth/v1/callback
- 检查是否有尾随斜杠
- 确保 HTTP 与 HTTPS 一致
问题:通行密钥无法在设备间同步
原因: 使用了错误的凭据附件类型创建凭据
解决方案:
// Use 'platform' for synced credentials
authenticatorAttachment: 'platform', // NOT 'cross-platform'
// 'cross-platform' = hardware security keys (no sync)
// 'platform' = device biometrics (sync via iCloud/Google)
安全最佳实践
令牌管理
// ✅ Good: Short-lived access tokens + refresh
const session = await supabase.auth.getSession();
// Access token: 1 hour
// Refresh token: 7 days (rotate on use)
// ✅ Good: Secure token storage
// Browser: HttpOnly cookies (Supabase handles this)
// Mobile: Secure Keychain/Keystore
// ❌ Bad: Long-lived tokens in localStorage
localStorage.setItem('token', longLivedToken); // DON'T
速率限制
// Implement rate limiting on auth endpoints
const rateLimit = {
signIn: { max: 5, windowMs: 15 * 60 * 1000 }, // 5 per 15 min
signUp: { max: 3, windowMs: 60 * 60 * 1000 }, // 3 per hour
passwordReset: { max: 3, windowMs: 60 * 60 * 1000 },
passkey: { max: 10, windowMs: 15 * 60 * 1000 },
};
安全默认设置
// Always verify email on signup
const { error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${origin}/auth/callback`,
// Supabase will only create confirmed user after email click
},
});
// Require email verification for sensitive actions
async function sensitiveAction(userId: string) {
const { data: user } = await supabase.auth.getUser();
if (!user?.email_confirmed_at) {
throw new Error('Please verify your email first');
}
// Proceed with action...
}
参考资料
官方文档
库
- SimpleWebAuthn - 推荐的 WebAuthn 库
- Corbado - 通行密钥即服务选项
- Hanko - 开源通行密钥服务