关于 authentication
authentication 是面向使用 NextAuth.js 的 Next.js 项目的认证与授权实践技能。它说明如何检查会话和用户角色、保护路由,以及更安全地处理令牌。
主要功能
- 01使用 auth() 获取当前会话
- 02为管理操作检查用户角色
- 03通过中间件保护路由
- 04使用 httpOnly Cookie 而非 localStorage 存储令牌
- 05在 API 路由中验证 JWT
适用场景
- 01要求 API 路由具备已登录会话
- 02按用户角色限制管理操作
- 03使用中间件保护路由
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ santiagoxor/ pintureria-digital --skill authentication安装后在 Claude Code 中输入/authentication确认已加载。
详细介绍
身份验证
快速入门
处理身份验证时:
- 使用
@/lib/auth中的auth()获取当前会话 - 执行管理操作前验证角色
- 使用中间件保护路由
- 切勿将令牌存储在 localStorage 中(使用 httpOnly Cookie)
- 在 API 路由中验证 JWT 令牌
关键文件
auth.ts- NextAuth.js 配置src/lib/auth/- 身份验证工具middleware.ts- 路由保护src/app/api/auth/- 身份验证 API 路由
常见模式
获取当前会话
import { auth } from '@/lib/auth';
export async function GET(request: NextRequest) {
const session = await auth();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ user: session.user });
}
检查管理员角色
const session = await auth();
if (session?.user?.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
受保护的 API 路由
import { auth } from '@/lib/auth';
import { NextRequest, NextResponse } from 'next/server';
export async function POST(request: NextRequest) {
// 1. Check authentication
const session = await auth();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// 2. Check authorization (if needed)
if (session.user.role !== 'admin') {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
// 3. Process request
const body = await request.json();
// ... business logic
}
中间件保护
// middleware.ts
import { auth } from '@/lib/auth';
import { NextResponse } from 'next/server';
export async function middleware(request: NextRequest) {
const session = await auth();
// Protect admin routes
if (request.nextUrl.pathname.startsWith('/admin')) {
if (!session || session.user.role !== 'admin') {
return NextResponse.redirect(new URL('/login', request.url));
}
}
return NextResponse.next();
}
登录/登出
import { signIn, signOut } from '@/lib/auth';
// Sign in
await signIn('google', {
callbackUrl: '/dashboard',
});
// Sign out
await signOut({
callbackUrl: '/',
});
用户角色
admin- 完全访问权限customer- 普通用户moderator- 有限的管理员访问权限
会话结构
interface Session {
user: {
id: string;
email: string;
name?: string;
role: 'admin' | 'customer' | 'moderator';
image?: string;
};
expires: string;
}
评论
支持 Markdown