Claude Code से सोशल लॉगिन लागू करें: Next.js, Auth.js, Google और GitHub OAuth
Claude Code के साथ सुरक्षित सोशल लॉगिन बनाएं: Next.js/Auth.js, Google/GitHub OAuth, काम करने वाला कोड और production pitfalls.
सोशल लॉगिन सिर्फ registration form छोटा करने की सुविधा नहीं है। जब user Google या GitHub OAuth से product में आता है, तब आप identity, account linking, session, cookie, CSRF, provider scope, audit log और support flow भी design कर रहे होते हैं। Claude Code को केवल “login बना दो” कहना अक्सर working button दे देता है, लेकिन redirect URI mismatch, unverified email से automatic linking, जरूरत से ज्यादा scope, या client secret का code में आ जाना जैसे जोखिम छोड़ सकता है।
यह guide Next.js App Router, Auth.js यानी NextAuth v5 style API, TypeScript और Prisma Adapter पर आधारित है। OAuth authorization code को ऐसे समझें: provider से मिला temporary code जिसे server token से exchange करता है। state CSRF रोकने के लिए random value है। redirect URI वह exact URL है जहां Google या GitHub browser को वापस भेजता है। account linking का मतलब है कि already logged-in user अपनी इच्छा से दूसरा login method उसी account से जोड़ता है।
पहले security boundary तय करें
पहला सवाल यह नहीं है कि कितने provider चाहिए। पहला सवाल है कि login से आप क्या prove करना चाहते हैं। SaaS, training site, internal tool या developer product में Google और GitHub काफी होते हैं। Google general users और company email के लिए अच्छा है। GitHub developer tools और technical community के लिए अच्छा है। Login के समय Google Drive, Calendar या GitHub repo scope मांगना conversion और trust दोनों को कम कर सकता है।
Claude Code को काम छोटे हिस्सों में दें:
- Auth.js provider, environment variables और callback route जोड़ना
- login page और protected page बनाना
- session में सिर्फ
user.idजोड़ना, access token नहीं - account linking सिर्फ logged-in settings page से शुरू करना
- last login method हटाने से रोकना
- client secret, refresh token और access token को code, log, issue या draft में न लिखना
Masa के test project में सबसे बड़ा issue generated code नहीं था। Google Cloud Console की redirect URI और app केAUTH_URL में हल्का अंतर था। Claude Code repository बदल सकता है, लेकिन external console values खुद से verify नहीं कर सकता। इसलिए URL, scope, email verification और cookie policy पहले checklist में लिखें।
OAuth flow को diagram से समझें
Google web app के लिए authorization code flow recommend करता है। Browser temporarycode लेता है और server client secret के साथ provider से token exchange करता है। client secret browser code में कभी नहीं जाना चाहिए।
sequenceDiagram
participant User as User
participant App as Next.js app
participant Auth as Auth.js route
participant Provider as Google or GitHub
User->>App: Click "Continue with Google"
App->>Auth: signIn("google")
Auth->>Provider: Redirect with client_id, redirect_uri, scope, state
Provider->>User: Consent screen
Provider->>Auth: Redirect back with code and state
Auth->>Provider: Exchange code on the server
Provider->>Auth: Return tokens
Auth->>App: Create session cookie
App->>User: Show dashboard
state यह साबित करता है कि callback उसी login request का result है जिसे app ने शुरू किया था। Auth.js standard routes इस्तेमाल करने पर यह काम framework संभालता है। अगर custom callback बनाना पड़े, तो Claude Code को साफ निर्देश दें कि state validate करना जरूरी है। GitHub documentation भी unpredictable state और mismatch पर flow रोकने की सलाह देता है।
Environment variables और minimum scope
यह configuration login के लिए है, extra API permission लेने के लिए नहीं। Google scopeopenid email profile है। GitHub scoperead:user user:email है।
npm install next-auth@beta @auth/prisma-adapter prisma @prisma/client
npx prisma init
npm exec auth secret
# .env.local
AUTH_SECRET="npm exec auth secret से बना value"
AUTH_URL="http://localhost:3000"
AUTH_GOOGLE_ID="Google Cloud Console client ID"
AUTH_GOOGLE_SECRET="Google Cloud Console client secret"
AUTH_GITHUB_ID="GitHub OAuth App client ID"
AUTH_GITHUB_SECRET="GitHub OAuth App client secret"
DATABASE_URL="postgresql://user:password@localhost:5432/app"
Example file में real value न रखें।
# .env.example
AUTH_SECRET=
AUTH_URL=
AUTH_GOOGLE_ID=
AUTH_GOOGLE_SECRET=
AUTH_GITHUB_ID=
AUTH_GITHUB_SECRET=
DATABASE_URL=
Google development redirect URIhttp://localhost:3000/api/auth/callback/google है। Production मेंhttps://example.com/api/auth/callback/google रखें। GitHub OAuth App मेंhttps://example.com/api/auth/callback/github रखें। Protocol, domain, path और provider name exact match होने चाहिए।
Auth.js configuration
नीचे का code Google login को तभी allow करता है जबemail_verified true हो। GitHub में email न मिले तो login reject होता है। Provider token browser session में नहीं भेजे जाते।
// auth.ts
import NextAuth, { type NextAuthConfig } from "next-auth";
import Google from "next-auth/providers/google";
import GitHub from "next-auth/providers/github";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { prisma } from "@/lib/prisma";
type GoogleProfile = {
sub: string;
name?: string;
email: string;
email_verified: boolean;
picture?: string;
};
export const authConfig = {
adapter: PrismaAdapter(prisma),
session: { strategy: "database" },
providers: [
Google({
authorization: {
params: {
scope: "openid email profile",
response_type: "code",
},
},
profile(profile: GoogleProfile) {
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture,
emailVerified: profile.email_verified ? new Date() : null,
};
},
}),
GitHub({
authorization: {
params: {
scope: "read:user user:email",
},
},
}),
],
callbacks: {
async signIn({ account, profile, user }) {
if (account?.provider === "google") {
const googleProfile = profile as GoogleProfile | undefined;
return Boolean(googleProfile?.email && googleProfile.email_verified);
}
if (account?.provider === "github") {
return Boolean(user.email);
}
return true;
},
async session({ session, user }) {
session.user.id = user.id;
return session;
},
},
pages: {
signIn: "/login",
error: "/login",
},
} satisfies NextAuthConfig;
export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);
// src/types/next-auth.d.ts
import "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
name?: string | null;
email?: string | null;
image?: string | null;
};
}
}
// src/app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
Prisma Adapter इस्तेमाल करते समय Claude Code कोUser, Account, Session, VerificationToken models भी add करने को कहें। Account table मेंprovider औरproviderAccountId account linking audit के लिए जरूरी हैं।
Login page और protected page
Server Action सेsignIn call करने पर request Auth.js standard flow में रहती है। Manual provider URL बनाना state और cookie mistakes बढ़ा सकता है।
// src/app/login/page.tsx
import { signIn } from "@/auth";
const providers = [
{ id: "google", label: "Google से जारी रखें" },
{ id: "github", label: "GitHub से जारी रखें" },
] as const;
export default function LoginPage({
searchParams,
}: {
searchParams: { error?: string };
}) {
return (
<main className="mx-auto flex min-h-screen max-w-sm flex-col justify-center gap-6 px-6">
<div>
<h1 className="text-2xl font-bold">Login</h1>
<p className="mt-2 text-sm text-gray-600">
इस application के लिए अपनी work identity चुनें।
</p>
</div>
{searchParams.error ? (
<p className="rounded-md bg-red-50 p-3 text-sm text-red-700">
Login failed. दूसरा account try करें या support से संपर्क करें।
</p>
) : null}
<div className="grid gap-3">
{providers.map((provider) => (
<form
key={provider.id}
action={async () => {
"use server";
await signIn(provider.id, { redirectTo: "/dashboard" });
}}
>
<button
type="submit"
className="w-full rounded-md border px-4 py-3 text-sm font-medium hover:bg-gray-50"
>
{provider.label}
</button>
</form>
))}
</div>
</main>
);
}
// src/app/dashboard/page.tsx
import { auth } from "@/auth";
import { redirect } from "next/navigation";
export default async function DashboardPage() {
const session = await auth();
if (!session?.user) {
redirect("/login");
}
return (
<main className="mx-auto max-w-3xl p-8">
<h1 className="text-2xl font-bold">Dashboard</h1>
<p className="mt-4 text-gray-700">
Signed in as {session.user.email}.
</p>
</main>
);
}
Account linking और unlink
सिर्फ email match होने पर accounts automatically link न करें। User पहले से logged in हो और settings page से link action शुरू करे। Unlink API same-origin check करे और last login method हटाने से रोके।
// src/app/api/settings/linked-accounts/route.ts
import { auth } from "@/auth";
import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";
function isSameOrigin(request: Request) {
const origin = request.headers.get("origin");
const host = request.headers.get("host");
if (!origin || !host) return false;
try {
return new URL(origin).host === host;
} catch {
return false;
}
}
export async function DELETE(request: Request) {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
if (!isSameOrigin(request)) {
return NextResponse.json({ error: "Bad origin" }, { status: 403 });
}
const body = (await request.json()) as { provider?: string };
const accounts = await prisma.account.findMany({
where: { userId: session.user.id },
select: { provider: true },
});
if (accounts.length <= 1) {
return NextResponse.json(
{ error: "Last login method remove नहीं किया जा सकता।" },
{ status: 400 },
);
}
await prisma.account.deleteMany({
where: { userId: session.user.id, provider: body.provider },
});
return NextResponse.json({ ok: true });
}
Claude Code prompt और review checklist
इस Next.js App Router app में Auth.js v5 के साथ Google/GitHub social login जोड़ें।
Requirements:
- client secret केवल .env.local या deployment secret से पढ़ें
- Google scope केवल openid email profile हो
- GitHub scope केवल read:user user:email हो
- Google login तभी allow हो जब email_verified true हो
- Session में केवल user.id जोड़ें, access_token client को न भेजें
- Account linking सिर्फ logged-in settings page से शुरू हो
- Last login method unlink न हो सके
- अंत में lint result और manual OAuth test steps बताएं
| Review point | क्या जांचें |
|---|---|
| OAuth flow | authorization code flow और exact redirect URI |
| state और CSRF | Auth.js standard route रहे, custom API same-origin check करे |
| Cookie और session | Tokens server-side रहें, production cookies Secure, HttpOnly, SameSite सोच के साथ हों |
| Account linking | verified email और explicit user action के बाद ही linking |
Real use cases
पहला use case B2B SaaS admin panel है। Google primary login हो सकता है, बाद में Workspace domain restriction और RBAC जोड़ सकते हैं। GitHub केवल technical users के लिए खुला रह सकता है।
दूसरा developer tool है। GitHub login onboarding छोटा करता है। Repository permission सिर्फ उस feature में मांगी जाती है जिसे सच में repo access चाहिए।
तीसरा existing email-password product है। Safe approach यह है कि logged-in user settings से Google या GitHub link करे। Logged-out state में same email देखकर accounts merge न करें।
चौथा training या webinar registration page है। Google verified email fake signups और manual confirmation कम कर सकता है।
Production में आम failures
redirect URI mismatch सबसे आम है। Local काम करे और production fail हो तोAUTH_URL, proxy Host header और Google/GitHub callback URL compare करें।
Email-based automatic linking risky है। Googleemail_verified देता है, पर हर provider समान assurance नहीं देता। Same email string को identity proof न मानें।
Excessive scopes PV और inquiry conversion घटाते हैं। User केवल login करना चाहता है, लेकिन repo या file permission देखकर छोड़ सकता है।
Client secret code में दिखे तो review रोकें। .env.local, deployment secrets या secret manager इस्तेमाल करें।
Google refresh token अलग design मांगता है। Google अक्सर पहली consent पर ही refresh token देता है। Pure login में इसे store न करें; background Google API के लिए token rotation अलग ticket बनाएं।
Official references और internal links
Implementation से पहले primary sources देखें: Auth.js, Google Identity Services OAuth, GitHub OAuth Apps, और OWASP Authentication Cheat Sheet।
Related guides: Claude Code OAuth implementation, JWT authentication, Claude Code security best practices, और environment variable management।
Consultation, training और verification points
ClaudeCodeLab team को login button से आगे ले जाकर reviewable authentication workflow बनाने में मदद करता है: requirements, Claude Code task design, code review, secret management और manual OAuth testing। Inquiry बढ़ानी हो तो implementation से पहले target user, provider, minimum permissions और error messages तय करें।
इस article को try करते समय verify करें कि development और production redirect URI exact match करते हैं, Googleemail_verified check हो रहा है, GitHub private email failure का clear message है, state और cookies Auth.js standard flow में हैं, last login method remove नहीं हो सकता, और client secret code या logs में नहीं दिखता।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.