Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计通过

nextauthnextauth 搜索

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

612

周安装

25

GitHub Stars

12

下载量

196
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:nextauth(nextauth 搜索)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/nextauth
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill nextauth
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill nextauth

简介

该技能用于审计 Next.js 应用的身份认证流程与安全配置。

  • 适用于登录系统设计、OAuth 集成与 JWT 令牌管理场景。
  • 检查回调 URL、state 参数与会话存储的安全性设置。
  • 需定期轮换 secret key 并使用 HTTPS 传输敏感数据。
  • 不能替代专业渗透测试,仅提供常见风险点自查清单。nextauth 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

NextAuth.js Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: nextauth for comprehensive documentation.

Basic Setup (App Router)

// app/api/auth/[...nextauth]/route.ts
import NextAuth from 'next-auth';
import { authOptions } from '@/lib/auth';

const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
// lib/auth.ts
import { NextAuthOptions } from 'next-auth';
import GoogleProvider from 'next-auth/providers/google';
import CredentialsProvider from 'next-auth/providers/credentials';
import { PrismaAdapter } from '@auth/prisma-adapter';
import { prisma } from './prisma';

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma),
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    }),
    CredentialsProvider({
      name: 'credentials',
      credentials: {
        email: { label: 'Email', type: 'email' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials) {
        const user = await prisma.user.findUnique({
          where: { email: credentials?.email },
        });
        if (user && await verifyPassword(credentials?.password, user.password)) {
          return user;
        }
        return null;
      },
    }),
  ],
  callbacks: {
    async session({ session, user }) {
      session.user.id = user.id;
      return session;
    },
  },
  pages: {
    signIn: '/login',
    error: '/auth/error',
  },
};

Client Usage

'use client';
import { useSession, signIn, signOut } from 'next-auth/react';

function AuthButton() {
  const { data: session, status } = useSession();

  if (status === 'loading') return <Spinner />;

  if (session) {
    return (
      <div>
        <span>{session.user?.email}</span>
        <button onClick={() => signOut()}>Sign out</button>
      </div>
    );
  }

  return <button onClick={() => signIn('google')}>Sign in</button>;
}

Server-Side Auth

// In Server Component
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

async function ProtectedPage() {
  const session = await getServerSession(authOptions);

  if (!session) {
    redirect('/login');
  }

  return <div>Welcome {session.user.name}</div>;
}

When NOT to Use This Skill

  • Generic OAuth 2.0 flows - Use oauth2 skill for platform-agnostic OAuth
  • Custom JWT implementation - Use jwt skill for custom token logic
  • Non-Next.js frameworks - Use framework-specific auth (Express Passport, etc.)
  • Remix/SvelteKit - Use their native auth solutions

Type Extensions

// types/next-auth.d.ts
declare module 'next-auth' {
  interface Session {
    user: { id: string; role: string } & DefaultSession['user'];
  }
}

Anti-Patterns

Anti-PatternWhy It's BadCorrect Approach
No NEXTAUTH_SECRETSecurity vulnerabilityAlways set in production
Client-side session checks onlyCan be bypassedUse getServerSession()
Hardcoded provider credentialsSecurity riskUse environment variables
No error handlingPoor UXImplement custom error pages
Mixing session strategiesInconsistent behaviorStick to JWT or database
No CSRF protectionVulnerable to attacksUse default CSRF (enabled by default)

Quick Troubleshooting

IssueCauseSolution
"Configuration error"Missing required env varsCheck NEXTAUTH_URL and NEXTAUTH_SECRET
Session is nullNot authenticated or session expiredCheck signIn() was called
"Callback URL error"Invalid redirectWhitelist URLs in provider settings
Type errorsMissing type extensionsCreate types/next-auth.d.ts
Session not updatingCache issueCall update() from useSession
CORS errorsWrong domainEnsure NEXTAUTH_URL matches deployment URL

Production Readiness

Security Configuration

// lib/auth.ts
import { NextAuthOptions } from 'next-auth';

export const authOptions: NextAuthOptions = {
  // Secure session configuration
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },

  // Secure cookies
  cookies: {
    sessionToken: {
      name: process.env.NODE_ENV === 'production'
        ? '__Secure-next-auth.session-token'
        : 'next-auth.session-token',
      options: {
        httpOnly: true,
        sameSite: 'lax',
        path: '/',
        secure: process.env.NODE_ENV === 'production',
      },
    },
  },

  // Callbacks for security
  callbacks: {
    async jwt({ token, user, account }) {
      if (user) {
        token.id = user.id;
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      session.user.id = token.id as string;
      session.user.role = token.role as string;
      return session;
    },
    async signIn({ user, account, profile }) {
      // Block suspicious sign-ins
      const isAllowed = await checkUserAllowed(user.email);
      return isAllowed;
    },
  },

  // Security events
  events: {
    async signIn({ user, account }) {
      await logSecurityEvent('signin', { userId: user.id, provider: account?.provider });
    },
    async signOut({ token }) {
      await logSecurityEvent('signout', { userId: token.sub });
    },
  },
};

Rate Limiting

// middleware.ts
import { NextResponse } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(5, '1 m'), // 5 requests per minute
});

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/api/auth')) {
    const ip = request.ip ?? '127.0.0.1';
    const { success, limit, reset, remaining } = await ratelimit.limit(ip);

    if (!success) {
      return new NextResponse('Too Many Requests', {
        status: 429,
        headers: {
          'X-RateLimit-Limit': limit.toString(),
          'X-RateLimit-Remaining': remaining.toString(),
          'X-RateLimit-Reset': reset.toString(),
        },
      });
    }
  }

  return NextResponse.next();
}

CSRF Protection

// lib/auth.ts
export const authOptions: NextAuthOptions = {
  // Enable CSRF token verification
  useSecureCookies: process.env.NODE_ENV === 'production',

  // Custom CSRF token
  callbacks: {
    async redirect({ url, baseUrl }) {
      // Only allow redirects to same origin
      if (url.startsWith('/')) return `${baseUrl}${url}`;
      if (new URL(url).origin === baseUrl) return url;
      return baseUrl;
    },
  },
};

// In API routes, verify CSRF
import { getToken } from 'next-auth/jwt';

export async function POST(request: Request) {
  const token = await getToken({ req: request });
  if (!token) {
    return new Response('Unauthorized', { status: 401 });
  }
  // Process request
}

Error Handling

// app/auth/error/page.tsx
'use client';

import { useSearchParams } from 'next/navigation';

const errorMessages: Record<string, string> = {
  Configuration: 'Server configuration error',
  AccessDenied: 'Access denied',
  Verification: 'Verification link expired',
  Default: 'Authentication error',
};

export default function AuthError() {
  const searchParams = useSearchParams();
  const error = searchParams.get('error') ?? 'Default';

  return (
    <div className="error-page">
      <h1>Authentication Error</h1>
      <p>{errorMessages[error] ?? errorMessages.Default}</p>
      <a href="/login">Try again</a>
    </div>
  );
}

Testing

// __tests__/auth.test.ts
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

// Mock next-auth
jest.mock('next-auth', () => ({
  getServerSession: jest.fn(),
}));

describe('Protected Route', () => {
  it('redirects unauthenticated users', async () => {
    (getServerSession as jest.Mock).mockResolvedValue(null);

    const response = await fetch('/api/protected');
    expect(response.status).toBe(401);
  });

  it('allows authenticated users', async () => {
    (getServerSession as jest.Mock).mockResolvedValue({
      user: { id: '1', email: 'test@example.com', role: 'user' },
    });

    const response = await fetch('/api/protected');
    expect(response.status).toBe(200);
  });
});

// E2E with Playwright
test('OAuth flow', async ({ page }) => {
  await page.goto('/login');
  await page.click('button:has-text("Sign in with Google")');

  // Mock OAuth provider response in test environment
  await expect(page).toHaveURL('/dashboard');
});

Monitoring Metrics

MetricTarget
Login success rate> 99%
Auth latency< 200ms
Failed login attemptsMonitor & alert
Token refresh success> 99.9%

Checklist

  • Secure cookie configuration
  • JWT with appropriate maxAge
  • Rate limiting on auth endpoints
  • CSRF protection enabled
  • Redirect URL validation
  • Security event logging
  • Custom error pages
  • Session refresh strategy
  • Role-based access control
  • Testing with mocked sessions

Reference Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.72%
按下载量换算66

Claude

28.11%
按下载量换算55

Cursor

18.81%
按下载量换算37

Gemini CLI

9.38%
按下载量换算18

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills