| name | build-auth-system |
| description | Build comprehensive API authentication and authorization system
|
| shortcut | auth |
| category | api |
| difficulty | intermediate |
| estimated_time | 5-10 minutes |
| version | 2.0.0 |
Build API Authentication System
Implements a complete authentication and authorization system for your API, supporting JWT tokens, OAuth2 flows, API keys, session-based auth, and multi-factor authentication. Generates production-ready auth middleware, user management, and role-based access control.
When to Use
Use this command when:
- Starting a new API that requires user authentication
- Adding authentication to an existing unprotected API
- Migrating from one auth method to another
- Implementing OAuth2 provider or consumer
- Adding multi-factor authentication (MFA/2FA)
- Setting up role-based or permission-based access control
- Building a SaaS application with tenant isolation
Do NOT use this command for:
- Static websites without user accounts
- Public APIs that don't require authentication
- Internal microservices using service mesh auth
- Simple basic auth for development environments
Prerequisites
Before running this command, ensure:
Process
Step 1: Analyze Authentication Requirements
Examines your application to determine the best auth strategy:
- Identifies user types and roles
- Determines session vs stateless requirements
- Evaluates security compliance needs
- Assesses scalability requirements
- Reviews existing auth infrastructure
Step 2: Generate Authentication Components
Creates the core authentication system:
- User model with secure password storage
- Authentication middleware/filters
- Token generation and validation
- Session management if required
- Password reset and recovery flows
Step 3: Implement Authorization Logic
Sets up access control mechanisms:
- Role-based access control (RBAC)
- Permission-based authorization
- Resource-level permissions
- API endpoint protection
- Tenant isolation for multi-tenant apps
Step 4: Configure Security Features
Implements additional security measures:
- Rate limiting for auth endpoints
- Account lockout after failed attempts
- Password complexity requirements
- Token refresh mechanisms
- Audit logging for auth events
Output Format
auth-system/
├── models/
│ ├── user.js # User model with auth fields
│ ├── role.js # Role definitions
│ └── permission.js # Permission mappings
├── middleware/
│ ├── authenticate.js # Auth verification middleware
│ ├── authorize.js # Permission checking
│ └── rate-limit.js # Rate limiting
├── services/
│ ├── auth.service.js # Core auth logic
│ ├── token.service.js # Token management
│ └── password.service.js # Password utilities
├── routes/
│ ├── auth.routes.js # Auth endpoints
│ └── user.routes.js # User management
├── config/
│ ├── auth.config.js # Auth configuration
│ └── jwt.config.js # JWT settings
└── tests/
└── auth.test.js # Auth system tests
Examples
Example 1: JWT-based Authentication for REST API
User Input:
/auth --type jwt --framework express
Generated Authentication Service:
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
class AuthService {
constructor() {
this.saltRounds = 12;
this.tokenExpiry = '1h';
this.refreshTokenExpiry = '7d';
}
async register(userData) {
this.validateRegistration(userData);
const existing = await User.findOne({ email: userData.email });
if (existing) {
throw new ConflictError('User already exists');
}
const hashedPassword = await bcrypt.hash(userData.password, this.saltRounds);
const user = .({
...userData,
: hashedPassword,
: crypto.().(),
: ,
: ()
});
.(user., user.);
{ accessToken, refreshToken } = .(user);
{
: .(user),
accessToken,
refreshToken
};
}
() {
user = .({ email }).();
(!user) {
();
}
isValid = bcrypt.(password, user.);
(!isValid) {
.(user);
();
}
(user. && user. > .()) {
();
}
(!user. && process.. === ) {
();
}
.(user);
{ accessToken, refreshToken } = .(user);
user. = ();
user.();
{
: .(user),
accessToken,
refreshToken
};
}
() {
payload = {
: user.,
: user.,
: user.
};
accessToken = jwt.(
payload,
process..,
{ : . }
);
refreshToken = jwt.(
{ : user., : },
process..,
{ : . }
);
.({
: user.,
: refreshToken,
: (.() + * * * * )
});
{ accessToken, refreshToken };
}
() {
decoded = jwt.(refreshToken, process..);
storedToken = .({
: refreshToken,
: decoded.,
: { : () }
});
(!storedToken) {
();
}
user = .(decoded.);
(!user) {
();
}
accessToken = jwt.(
{
: user.,
: user.,
: user.
},
process..,
{ : . }
);
{ accessToken };
}
() {
.({ userId, : refreshToken });
.({
: refreshToken,
: (.() + * * * * )
});
{ : };
}
}
Generated Middleware:
const jwt = require('jsonwebtoken');
const authenticate = async (req, res, next) => {
try {
const token = extractToken(req);
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
const isBlacklisted = await BlacklistedToken.exists({ token });
if (isBlacklisted) {
return res.status(401).json({ error: 'Token revoked' });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(decoded.id).select('-password');
if (!user) {
return res.status(401).json({ error: });
}
req. = user;
req. = user.;
();
} (error) {
(error. === ) {
res.().({ : });
}
(error. === ) {
res.().({ : });
}
res.().({ : });
}
};
= () => {
{
(!req.) {
res.().({ : });
}
hasRole = req...( allowedRoles.(role));
(!hasRole) {
res.().({ : });
}
();
};
};
Example 2: OAuth2 Provider Implementation
User Input:
/auth --type oauth2-provider --framework fastapi
Generated OAuth2 Provider:
from datetime import datetime, timedelta
from typing import Optional
import secrets
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from sqlalchemy.orm import Session
class OAuth2Provider:
def __init__(self):
self.pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
self.oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
self.SECRET_KEY = os.getenv("SECRET_KEY")
self.ALGORITHM = "HS256"
self.ACCESS_TOKEN_EXPIRE_MINUTES = 30
self.REFRESH_TOKEN_EXPIRE_DAYS = 7
async def create_client(self, client_data: dict, db: Session):
"""Register OAuth2 client application"""
client = OAuth2Client(
client_id=secrets.token_urlsafe(32),
client_secret=self.hash_secret(secrets.token_urlsafe(64)),
name=client_data[],
redirect_uris=client_data[],
grant_types=client_data[],
response_types=client_data[],
scope=client_data[],
created_at=datetime.utcnow()
)
db.add(client)
db.commit()
client
():
client = db.query(OAuth2Client).(
OAuth2Client.client_id == client_id
).first()
client redirect_uri client.redirect_uris:
HTTPException(
status_code=,
detail=
)
auth_code = AuthorizationCode(
code=secrets.token_urlsafe(),
client_id=client_id,
user_id=user.,
redirect_uri=redirect_uri,
scope=scope,
expires_at=datetime.utcnow() + timedelta(minutes=)
)
db.add(auth_code)
db.commit()
auth_code.code
():
client = .verify_client(client_id, client_secret, db)
auth_code = db.query(AuthorizationCode).(
AuthorizationCode.code == code,
AuthorizationCode.client_id == client_id,
AuthorizationCode.redirect_uri == redirect_uri,
AuthorizationCode.expires_at > datetime.utcnow()
).first()
auth_code:
HTTPException(
status_code=,
detail=
)
access_token = .create_access_token(
data={: (auth_code.user_id), : auth_code.scope}
)
refresh_token = .create_refresh_token(
data={: (auth_code.user_id)}
)
db.delete(auth_code)
db.commit()
{
: access_token,
: refresh_token,
: ,
: .ACCESS_TOKEN_EXPIRE_MINUTES *
}
Example 3: API Key Authentication
User Input:
/auth --type api-key --with-rate-limiting
Generated API Key System:
const crypto = require('crypto');
const { RateLimiter } = require('./rate-limiter');
class APIKeyService {
constructor() {
this.rateLimiter = new RateLimiter();
}
async generateAPIKey(userId, name, permissions = []) {
const apiKey = `sk_${process.env.NODE_ENV}_${crypto.randomBytes(32).toString('hex')}`;
const hashedKey = crypto
.createHash('sha256')
.update(apiKey)
.digest('hex');
const keyRecord = await APIKey.create({
userId,
name,
keyHash: hashedKey,
prefix: apiKey.substring(0, 7),
permissions,
lastUsed: null,
expiresAt: null,
createdAt: new ()
});
{
: keyRecord.,
apiKey,
name,
permissions,
: keyRecord.
};
}
() {
hashedKey = crypto
.()
.(apiKey)
.();
keyRecord = .({
: hashedKey,
: [
{ : },
{ : { : () } }
]
});
(!keyRecord) {
();
}
rateLimitOk = ..(
keyRecord.,
keyRecord. ||
);
(!rateLimitOk) {
();
}
keyRecord. = ();
keyRecord. += ;
keyRecord.();
user = .(keyRecord.);
{
user,
: keyRecord.,
: keyRecord.
};
}
}
Error Handling
Error: Password Too Weak
Symptoms: Registration fails with password validation error
Cause: Password doesn't meet complexity requirements
Solution:
const passwordStrength = {
minLength: 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSymbols: true
};
Error: Token Expired
Symptoms: 401 Unauthorized after token lifetime
Cause: Access token has expired
Solution:
const { accessToken } = await authService.refreshAccessToken(refreshToken);
Error: Account Locked
Symptoms: 403 Forbidden after multiple failed attempts
Cause: Brute force protection triggered
Solution:
const lockoutDuration = Math.pow(2, failedAttempts) * 60 * 1000;
Configuration Options
Option: --type
- Purpose: Choose authentication method
- Values:
jwt, oauth2, api-key, session, basic
- Default:
jwt
- Example:
/auth --type oauth2
Option: --with-mfa
- Purpose: Add multi-factor authentication
- Default: false
- Example:
/auth --with-mfa
Option: --with-social
- Purpose: Add social login providers
- Default: false
- Example:
/auth --with-social google,github,facebook
Best Practices
✅ DO:
- Hash passwords with bcrypt or argon2
- Use secure random tokens
- Implement rate limiting
- Log authentication events
- Use HTTPS only
- Validate email addresses
- Implement password reset flow
❌ DON'T:
- Store plain text passwords
- Use MD5 or SHA1 for passwords
- Create predictable tokens
- Log sensitive information
- Allow unlimited login attempts
- Trust client-side validation only
💡 TIPS:
- Use refresh tokens for better UX
- Implement remember me functionality carefully
- Add CAPTCHA for public endpoints
- Monitor for suspicious activity
- Implement session invalidation
Related Commands
/api-rate-limiter - Add rate limiting to APIs
/api-security-scanner - Scan for vulnerabilities
/user-management - User CRUD operations
/session-manager - Session handling utilities
Performance Considerations
- Token generation: <50ms
- Password hashing: 100-300ms (intentionally slow)
- Token validation: <10ms
- Session lookup: <5ms with caching
Security Notes
⚠️ Security Considerations:
- Always use HTTPS in production
- Store secrets in environment variables
- Rotate JWT secrets regularly
- Implement CSRF protection
- Use secure session cookies
- Enable CORS appropriately
- Audit authentication logs
Troubleshooting
Issue: JWT secret not set
Solution: Set JWT_SECRET environment variable with strong random value
Issue: Sessions not persisting
Solution: Configure session store (Redis recommended for production)
Issue: OAuth2 redirect not working
Solution: Verify redirect URI is whitelisted in OAuth2 provider
Version History
- v2.0.0 - Complete rewrite with multiple auth methods
- v1.0.0 - Basic JWT implementation
Last updated: 2025-10-11
Quality score: 9+/10
Tested with: Express, FastAPI, Django, Spring Boot