Implement secure authentication with multiple providers
# Authentication Patterns Complete Guide for Google Antigravity
Implement secure, user-friendly authentication using Google Antigravity IDE.
## NextAuth.js Configuration
```typescript
// app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth";
import GoogleProvider from "next-auth/providers/google";
import GitHubProvider from "next-auth/providers/github";
import CredentialsProvider from "next-auth/providers/credentials";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import { db } from "@/lib/db";
import { verifyPassword } from "@/lib/auth";
export const authOptions = {
adapter: DrizzleAdapter(db),
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!
}),
GitHubProvider({
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!
}),
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Invalid credentials");
}
const user = await db.query.users.findFirst({
where: eq(users.email, credentials.email)
});
if (!user || !user.password) {
throw new Error("Invalid credentials");
}
const isValid = await verifyPassword(credentials.password, user.password);
if (!isValid) {
throw new Error("Invalid credentials");
}
return { id: user.id, email: user.email, name: user.name };
}
})
],
callbacks: {
async jwt({ token, user, account }) {
if (user) {
token.id = user.id;
token.role = user.role;
}
return token;
},
async session({ session, token }) {
if (token) {
session.user.id = token.id;
session.user.role = token.role;
}
return session;
}
},
pages: {
signIn: "/login",
error: "/auth/error"
},
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60 // 30 days
}
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
```
## Protected Routes Middleware
```typescript
// middleware.ts
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
const publicPaths = ["/", "/login", "/signup", "/forgot-password"];
const adminPaths = ["/admin"];
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// Allow public paths
if (publicPaths.some(path => pathname.startsWith(path))) {
return NextResponse.next();
}
const token = await getToken({
req: request,
secret: process.env.NEXTAUTH_SECRET
});
// Redirect to login if not authenticated
if (!token) {
const loginUrl = new URL("/login", request.url);
loginUrl.searchParams.set("callbackUrl", pathname);
return NextResponse.redirect(loginUrl);
}
// Check admin routes
if (adminPaths.some(path => pathname.startsWith(path))) {
if (token.role !== "admin") {
return NextResponse.redirect(new URL("/", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"]
};
```
## Auth Hook
```typescript
// hooks/useAuth.ts
"use client";
import { useSession, signIn, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
export function useAuth() {
const { data: session, status } = useSession();
const router = useRouter();
const login = async (email: string, password: string) => {
const result = await signIn("credentials", {
email,
password,
redirect: false
});
if (result?.error) {
throw new Error(result.error);
}
router.push("/dashboard");
};
const loginWithProvider = (provider: "google" | "github") => {
signIn(provider, { callbackUrl: "/dashboard" });
};
const logout = () => {
signOut({ callbackUrl: "/" });
};
return {
user: session?.user,
isAuthenticated: !!session,
isLoading: status === "loading",
login,
loginWithProvider,
logout
};
}
```
## Best Practices
1. **Use secure session management** with JWT or database sessions
2. **Implement CSRF protection** for forms
3. **Hash passwords** with bcrypt or argon2
4. **Use OAuth** for third-party authentication
5. **Implement rate limiting** on auth endpoints
6. **Add two-factor authentication** for sensitive accounts
7. **Log authentication events** for security auditing
Google Antigravity helps implement secure authentication patterns with proper session management.This authentication prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their authentication implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For authentication projects, consider mentioning your framework version, coding style, and any specific libraries you're using.