Overview
The authentication flow consists of four main phases:Phase 1: Authorization request
When a user needs to sign in, your application generates an authorization URL and redirects them to WorkOS AuthKit.Generating the authorization URL
ThegetAuthorizationUrl() function creates a properly formatted OAuth 2.0 authorization URL:
- screenHint - Whether to show the sign-in or sign-up screen
- returnPathname - Where to redirect after successful authentication
- organizationId - Specific organization for SSO flows
- loginHint - Pre-fill the email field
- state - Custom state to pass through the flow
State management
AuthKit automatically manages OAuth state to ensure security and proper return navigation. The state parameter includes:- Internal state - Encoded return pathname for post-auth navigation
- Custom state - Optional user-provided state data
The middleware automatically determines the correct redirect URI from your configuration. You can override it per-request if needed.
Phase 2: User authentication
Once redirected to AuthKit, the user authenticates using one of several methods:- Password authentication - Email and password
- Magic link - Passwordless email authentication
- SSO - SAML or OAuth connections
- Social login - Google, Microsoft, GitHub, etc.
- MFA - Multi-factor authentication if required
Phase 3: Callback handling
After successful authentication, WorkOS AuthKit redirects back to your callback route with an authorization code.Setting up the callback route
Create a callback route handler using thehandleAuth() function:
app/api/auth/callback/route.ts
- code - Authorization code to exchange for tokens
- state - The state parameter sent in the initial request
Callback processing
When the callback route is hit,handleAuth() performs these operations:
Here’s what happens in the code:
Custom callback handling
You can hook into the callback flow with custom logic:Phase 4: Token exchange
The authorization code is exchanged for two tokens:Access token
A short-lived JWT (typically 5-10 minutes) that contains:- User information - User ID, email, name
- Session ID - Unique identifier for this session
- Organization context - Organization ID and role
- Permissions - User’s permissions array
- Entitlements - Active feature entitlements
- Feature flags - Enabled feature flags
Refresh token
A long-lived opaque token used to obtain new access tokens when they expire. Refresh tokens:- Are stored securely in an encrypted session cookie
- Never exposed to the client-side JavaScript
- Can be revoked by WorkOS if the session is terminated
Security considerations
Session encryption
Session encryption
Sessions are encrypted using
iron-session with a 32+ character password. This ensures tokens cannot be read or tampered with by clients.Cookie security
Cookie security
State validation
State validation
The OAuth state parameter prevents CSRF attacks by ensuring the callback matches the original request. State is validated on return.
Token verification
Token verification
Access tokens are cryptographically verified using WorkOS’s public keys before trusting their contents.
Error handling
Authentication can fail at several points:Authorization errors
- Missing configuration - Required environment variables not set
- Invalid redirect URI - Callback URL doesn’t match configuration
- SSO errors - Organization requires SSO but connection is misconfigured
Callback errors
- Missing code - No authorization code in callback URL
- Invalid code - Code already used or expired
- Network errors - Unable to reach WorkOS API
Token errors
- Invalid tokens - Malformed or corrupted tokens
- Expired tokens - Access token expired (handled automatically by refresh)
onError callback:
Next steps
Session management
Learn how sessions are maintained and refreshed
Middleware
Understand how middleware protects your routes