mcpField
A
authentication

authentication

github.com/santiagoxor安全35 次安装
代码仓库

关于 authentication

authentication 是面向使用 NextAuth.js 的 Next.js 项目的认证与授权实践技能。它说明如何检查会话和用户角色、保护路由,以及更安全地处理令牌。

主要功能

  1. 01使用 auth() 获取当前会话
  2. 02为管理操作检查用户角色
  3. 03通过中间件保护路由
  4. 04使用 httpOnly Cookie 而非 localStorage 存储令牌
  5. 05在 API 路由中验证 JWT

适用场景

  1. 01要求 API 路由具备已登录会话
  2. 02按用户角色限制管理操作
  3. 03使用中间件保护路由

安装

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

$npx skills add https://github.com/santiagoxor/pintureria-digital --skill authentication

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

详细介绍

身份验证

快速入门

处理身份验证时:

  1. 使用 @/lib/auth 中的 auth() 获取当前会话
  2. 执行管理操作前验证角色
  3. 使用中间件保护路由
  4. 切勿将令牌存储在 localStorage 中(使用 httpOnly Cookie)
  5. 在 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