Add API Authentication with AI Prompts

TL;DR

These prompts help you add authentication to your API endpoints. They cover JWT tokens, API keys, session-based auth, and OAuth integration. Choose the right approach for your use case and implement it securely.

JWT Authentication

Use this prompt to add JWT-based authentication to your API. Your AI will generate login, refresh, and logout endpoints along with token validation middleware and secure secret management.

AI Prompt

JWT Authentication Setup

Add JWT authentication to my API.

Requirements:

  1. Generate tokens on login with proper claims (sub, iat, exp)
  2. Use a secure signing algorithm (RS256 or HS256 with strong secret)
  3. Create middleware to validate tokens on protected routes
  4. Handle token expiration and refresh tokens
  5. Store refresh tokens securely (httpOnly cookies or database)

Implementation:

  • Login endpoint that returns access + refresh tokens
  • Token refresh endpoint
  • Logout endpoint that invalidates refresh token
  • Protected route middleware
  • Error handling for expired/invalid tokens

Security considerations:

  • Short access token expiry (15 min)
  • Longer refresh token expiry (7 days)
  • Rotate refresh tokens on use
  • Store secret in environment variable

API Key Authentication

Paste this prompt to generate a complete API key system for server-to-server communication. You'll get key generation, hashed storage, validation middleware, revocation, and scoped permissions.

AI Prompt

API Key Authentication

Add API key authentication for server-to-server communication.

Requirements:

  1. Generate cryptographically secure API keys
  2. Store hashed keys in database (not plaintext)
  3. Accept keys via Authorization header or X-API-Key
  4. Validate and rate limit per key
  5. Track key usage (last used, request count)

Features needed:

  • Key generation endpoint (admin only)
  • Key validation middleware
  • Key revocation endpoint
  • Usage statistics per key
  • Scoped permissions (read, write, admin)

Key format: prefix_random_bytes Example: sk_live_abc123def456

Session-Based Authentication

Use this prompt to set up server-side session authentication with secure cookies. Your AI will create session creation, validation middleware, CSRF protection, and secure cookie configuration.

AI Prompt

Session Authentication

Add session-based authentication to my web application API.

Requirements:

  1. Create session on successful login
  2. Store session server-side (Redis or database)
  3. Send session ID via httpOnly, secure cookie
  4. Validate session on each request
  5. Implement secure logout (destroy session)

Security settings:

  • httpOnly: true (prevent XSS access)
  • secure: true (HTTPS only)
  • sameSite: 'strict' or 'lax'
  • Rotate session ID on login (prevent fixation)
  • Set reasonable expiry with sliding window

Also implement:

  • Session middleware
  • CSRF protection for state-changing requests
  • Concurrent session limiting (optional)

OAuth Integration

Copy this prompt to generate a full OAuth 2.0 authorization code flow for Google or GitHub. You'll get redirect endpoints, callback handlers, state parameter validation, PKCE support, and user account creation logic.

AI Prompt

OAuth Setup

Add OAuth authentication (Google/GitHub) to my application.

Provider: Google / GitHub / both

Requirements:

  1. Implement OAuth 2.0 authorization code flow
  2. Securely handle state parameter (CSRF protection)
  3. Exchange code for tokens server-side
  4. Create or link user account
  5. Issue application JWT/session after OAuth success

Implement:

  • /auth/provider - redirect to OAuth provider
  • /auth/provider/callback - handle OAuth callback
  • State generation and validation
  • Token exchange logic
  • User creation/linking logic

Security:

  • Validate state parameter
  • Use PKCE if supported
  • Store tokens securely (or don't store if not needed)
  • Don't expose client secret to frontend

Never trust the frontend: Always validate authentication server-side. Client-side tokens can be manipulated. The server must verify every request independently.

Framework-Specific Implementation

Next.js

This prompt asks your AI to scaffold authentication for a Next.js App Router project. You'll get an auth configuration file, login/logout API routes, a session provider, and a useAuth hook or middleware for route protection.

AI Prompt

Next.js Auth Setup

Add authentication to my Next.js application.

Using: NextAuth.js / custom / Clerk / Auth0

For App Router:

  1. Create auth configuration
  2. Implement server-side session checking
  3. Create protected API routes
  4. Add middleware for route protection
  5. Handle auth state on client

Create:

  • Auth configuration file
  • Login/logout API routes
  • Session provider wrapper
  • useAuth hook or server-side helpers
  • Protected route wrapper/middleware

Pro tip: For user-facing apps, consider using established auth providers (NextAuth, Clerk, Auth0) rather than rolling your own. They handle edge cases you might not think of.

Should I use JWT or sessions?

Sessions are simpler and easier to revoke. JWTs are stateless and scale better for distributed systems. For most web apps, sessions work great. For APIs with third-party clients, JWTs or API keys are better.

How long should tokens be valid?

Access tokens: 15 minutes to 1 hour. Refresh tokens: 7 to 30 days. Shorter is more secure but requires more refresh logic. Balance security with user experience.

Where should I store tokens on the client?

HttpOnly cookies are most secure against XSS. If using localStorage, ensure strict CSP. Never store tokens in sessionStorage for persistent auth.

Test Your Auth Security

Scan your authentication implementation for vulnerabilities.

AI Fix Prompts

Add API Authentication with AI Prompts