Sample Application using React
A Next.js application with OAuth 2.0 Single Sign-On (SSO) integration using the Authorization Code Flow.
Features
- OAuth 2.0 Authorization Code Flow with PKCE
- Single Sign-On (SSO) integration with z-Pax
- Secure token management using NextAuth.js
- Protected routes with middleware
- Session management with JWT
- Beautiful, modern UI with Tailwind CSS
- TypeScript support
- User profile and authentication status display
Prerequisites
- Node.js 18+ (recommended)
- npm or yarn
- z-Pax OAuth application credentials (Client ID and Client Secret)
Getting Started
1. Install Dependencies
npm install2. Configure Environment Variables
Create a .env.local file in the root directory:
# NextAuth Configuration
NEXTAUTH_URL=http://localhost:3000
NEXTAUTH_SECRET=your-secret-key-here
# OAuth 2.0 Provider Configuration (z-Pax)
ZPAX_CLIENT_ID=your-zpax-client-id
ZPAX_CLIENT_SECRET=your-zpax-client-secret
ZPAX_ISSUER=https://your-zpax-domain.com
ZPAX_AUTHORIZATION_URL=https://your-zpax-domain.com/oauth/authorize
ZPAX_TOKEN_URL=https://your-zpax-domain.com/oauth/token
ZPAX_USERINFO_URL=https://your-zpax-domain.com/oauth/userinfoGenerate NEXTAUTH_SECRET
Run this command to generate a secure secret:
openssl rand -base64 323. Configure z-Pax OAuth Application
- Register your application with z-Pax
- Set the redirect URI to:
http://localhost:3000/api/auth/callback/zpax - Obtain your Client ID and Client Secret
- Update the
.env.localfile with your credentials
4. Run the Development Server
npm run devOpen http://localhost:3000 with your browser to see the application.
Project Structure
src/
├── app/
│ ├── api/
│ │ └── auth/
│ │ └── [...nextauth]/
│ │ └── route.ts # NextAuth configuration
│ ├── auth/
│ │ ├── signin/
│ │ │ └── page.tsx # Sign-in page
│ │ ├── signout/
│ │ │ └── page.tsx # Sign-out page
│ │ └── error/
│ │ └── page.tsx # Error page
│ ├── dashboard/
│ │ └── page.tsx # Protected dashboard
│ ├── layout.tsx # Root layout
│ ├── page.tsx # Home page
│ └── globals.css # Global styles
├── components/
│ ├── Header.tsx # Navigation header
│ └── SessionProvider.tsx # Session provider wrapper
├── types/
│ └── next-auth.d.ts # NextAuth type definitions
└── middleware.ts # Route protection middleware
OAuth 2.0 Authorization Code Flow
This application implements the OAuth 2.0 Authorization Code Flow, which is the most secure OAuth flow for web applications. Here's how it works:
Flow Steps
- Authorization Request: User clicks "Sign In" and is redirected to the z-Pax authorization endpoint
- User Authentication: User authenticates with their z-Pax credentials
- Authorization Grant: z-Pax redirects back with an authorization code
- Token Exchange: Application exchanges the code for tokens (access token, ID token)
- User Info: Application fetches user profile information
- Session Creation: Secure session is established using JWT
Security Features
- PKCE (Proof Key for Code Exchange): Adds extra security layer
- State Parameter: Prevents CSRF attacks
- Secure Token Storage: Tokens stored in HTTP-only cookies
- JWT Sessions: Stateless session management
- Middleware Protection: Automatic route protection
Available Routes
Public Routes
/- Home page with authentication status/auth/signin- Sign-in page/auth/signout- Sign-out page/auth/error- Authentication error page
Protected Routes
/dashboard- Protected dashboard (requires authentication)/api/protected/*- Protected API routes
Customization
Adding Protected Routes
Edit src/middleware.ts to add more protected routes:
export const config = {
matcher: [
"/dashboard/:path*",
"/profile/:path*",
"/api/protected/:path*",
"/your-route/:path*", // Add your route here
],
};Configuring OAuth Provider
Edit src/app/api/auth/[...nextauth]/route.ts to customize the OAuth provider configuration:
const zpaxProvider = {
id: "zpax",
name: "z-Pax",
// ... other configuration
authorization: {
url: process.env.ZPAX_AUTHORIZATION_URL,
params: {
scope: "openid profile email", // Customize scopes
response_type: "code",
},
},
// ...
};Adding Multiple OAuth Providers
You can add additional OAuth providers in the NextAuth configuration:
export const authOptions: NextAuthOptions = {
providers: [
zpaxProvider,
// Add more providers here
],
// ...
};API Endpoints
Authentication
GET /api/auth/signin- Initiate sign-inGET /api/auth/signout- Sign outGET /api/auth/callback/zpax- OAuth callback handlerGET /api/auth/session- Get current sessionGET /api/auth/csrf- Get CSRF token
Session Management
The application uses JWT-based sessions with the following configuration:
- Strategy: JWT (stateless)
- Max Age: 30 days
- Secure: HTTP-only cookies
- Same Site: Lax
Troubleshooting
Common Issues
-
"Configuration" Error
- Check that all environment variables are set correctly
- Verify OAuth endpoints are accessible
-
"AccessDenied" Error
- User denied permission during OAuth flow
- Check OAuth scope requirements
-
Redirect URI Mismatch
- Ensure redirect URI in z-Pax matches:
http://localhost:3000/api/auth/callback/zpax
- Ensure redirect URI in z-Pax matches:
-
Invalid Client Credentials
- Verify Client ID and Client Secret are correct
- Check that credentials haven't expired
Debug Mode
Enable debug mode in development by setting:
NODE_ENV=developmentThis will output detailed logs from NextAuth.js to the console.
Production Deployment
Environment Variables
For production, update these variables:
NEXTAUTH_URL=https://your-production-domain.com
NEXTAUTH_SECRET=your-production-secretBuild and Deploy
HTTP Deployment (Development/Staging)
npm run build
npm startHTTPS Production Deployment
This project includes comprehensive HTTPS support for production:
# 1. Generate SSL certificates (for development/testing)
npm run ssl:generate
# 2. Build for production
npm run build:prod
# 3. Start HTTPS server on port 443
npm run start:https
# Or run both commands:
npm run prodHTTPS Configuration
For HTTPS production deployment, see PRODUCTION_HTTPS.md for detailed instructions including:
- SSL certificate generation and management
- Docker deployment with HTTPS
- Nginx reverse proxy setup
- Environment variable configuration
Vercel Deployment
This project is optimized for deployment on Vercel:
- Push your code to GitHub
- Import the repository in Vercel
- Add environment variables in Vercel dashboard
- Deploy
Note: Vercel automatically provides HTTPS certificates, so manual SSL configuration is not needed.
Remember to update the redirect URI in your z-Pax OAuth application to match your production domain.
Learn More
License
MIT License
Support
For issues and questions, please refer to the OAUTH_SETUP.md file for detailed setup instructions.