JWT compliance is crucial for enterprise applications and regulated industries. Here are main compliance requirements and implementation methods:
1. GDPR Compliance
Data Minimization Principle
javascript// ❌ Non-compliant with GDPR: storing too much personal info const token = jwt.sign({ userId: '123', username: 'john.doe@example.com', fullName: 'John Doe', address: '123 Main St', phone: '+1234567890', ssn: '123-45-6789' // Sensitive information }, SECRET_KEY); // ✅ GDPR compliant: only store necessary information const token = jwt.sign({ sub: '123', // subject, user unique identifier iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 3600 }, SECRET_KEY);
Right to Deletion
javascript// Implement user data deletion async function deleteUserAccount(userId) { // 1. Invalidate all user tokens await invalidateAllUserTokens(userId); // 2. Delete user data await db.delete('users', { id: userId }); await db.delete('user_sessions', { userId }); // 3. Log deletion operation (audit log) await logDataDeletion(userId, 'user_request'); return { success: true }; }
Right to Access
javascript// Implement data export functionality async function exportUserData(userId) { const userData = { profile: await db.get('users', { id: userId }), sessions: await db.get('user_sessions', { userId }), activity: await db.get('user_activity', { userId }), exportDate: new Date().toISOString() }; return userData; }
2. HIPAA Compliance
Protected Health Information (PHI) Handling
javascript// ❌ Non-compliant with HIPAA: storing PHI in JWT const token = jwt.sign({ userId: '123', patientName: 'John Doe', diagnosis: 'Hypertension', medications: ['Lisinopril', 'Amlodipine'] }, SECRET_KEY); // ✅ HIPAA compliant: only store reference ID const token = jwt.sign({ sub: '123', scope: 'patient.read', aud: 'healthcare-api' }, SECRET_KEY); // PHI stored in secure database const patientData = await db.get('patients', { id: '123' });
Audit Logging
javascript// Log all PHI access async function logPHIAccess(userId, patientId, action) { await db.insert('audit_log', { userId, patientId, action, timestamp: new Date().toISOString(), ip: req.ip, userAgent: req.headers['user-agent'], accessedFields: ['diagnosis', 'medications'] }); } // Usage example app.get('/api/patients/:id', authMiddleware, async (req, res) => { const patient = await db.get('patients', { id: req.params.id }); // Log access await logPHIAccess(req.user.userId, req.params.id, 'READ'); res.json(patient); });
Principle of Least Privilege
javascript// Implement fine-grained permission control function requirePHIAccess(requiredScope) { return (req, res, next) => { const userScope = req.user.scope || []; if (!userScope.includes(requiredScope)) { return res.status(403).json({ error: 'INSUFFICIENT_PERMISSIONS', message: 'You do not have permission to access this resource' }); } next(); }; } // Usage example app.get('/api/patients/:id', authMiddleware, requirePHIAccess('patient.read'), async (req, res) => { const patient = await db.get('patients', { id: req.params.id }); res.json(patient); } );
3. PCI DSS Compliance
Don't Store Sensitive Information
javascript// ❌ Non-compliant with PCI DSS: storing card number in JWT const token = jwt.sign({ userId: '123', cardNumber: '4111111111111111', expiry: '12/25', cvv: '123' }, SECRET_KEY); // ✅ PCI DSS compliant: only store tokenized reference const token = jwt.sign({ sub: '123', paymentToken: 'tok_1abc2def3ghi', scope: 'payment.process' }, SECRET_KEY);
Encrypted Transmission
javascript// Enforce HTTPS const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('certificate.pem'), ca: fs.readFileSync('ca-bundle.crt') }; const server = https.createServer(options, app); // HTTP to HTTPS redirect app.use((req, res, next) => { if (!req.secure) { return res.redirect(`https://${req.headers.host}${req.url}`); } next(); });
Secure Key Management
javascript// Use AWS KMS for key management const AWS = require('aws-sdk'); const kms = new AWS.KMS(); async function encryptData(data) { const params = { KeyId: process.env.KMS_KEY_ID, Plaintext: Buffer.from(data) }; const result = await kms.encrypt(params).promise(); return result.CiphertextBlob.toString('base64'); } async function decryptData(encryptedData) { const params = { CiphertextBlob: Buffer.from(encryptedData, 'base64') }; const result = await kms.decrypt(params).promise(); return result.Plaintext.toString(); }
4. SOC 2 Compliance
Access Control
javascript// Implement Role-Based Access Control (RBAC) const roles = { admin: ['read', 'write', 'delete', 'manage'], user: ['read', 'write'], guest: ['read'] }; function checkPermission(user, requiredPermission) { const userRole = user.role || 'guest'; const userPermissions = roles[userRole] || []; return userPermissions.includes(requiredPermission); } // Middleware function requirePermission(permission) { return (req, res, next) => { if (!checkPermission(req.user, permission)) { return res.status(403).json({ error: 'FORBIDDEN', message: 'Insufficient permissions' }); } next(); }; }
Audit Trail
javascript// Comprehensive audit logging async function auditLog(event, data) { const logEntry = { event, data, timestamp: new Date().toISOString(), userId: data.userId, ipAddress: data.ip, userAgent: data.userAgent, sessionId: data.sessionId }; // Store to immutable log storage await appendToAuditLog(logEntry); // Also send to SIEM system await sendToSIEM(logEntry); } // Usage example app.post('/api/users', authMiddleware, async (req, res) => { const user = await createUser(req.body); await auditLog('USER_CREATED', { userId: req.user.userId, targetUserId: user.id, ip: req.ip, userAgent: req.headers['user-agent'] }); res.json(user); });
Change Management
javascript// Log configuration changes async function logConfigChange(configKey, oldValue, newValue, userId) { await db.insert('config_changes', { configKey, oldValue, newValue, userId, timestamp: new Date().toISOString(), changeType: 'MODIFICATION' }); } // Usage example async function updateJWTConfig(newConfig) { const oldConfig = await getCurrentJWTConfig(); await logConfigChange( 'jwt_config', oldConfig, newConfig, req.user.userId ); await saveJWTConfig(newConfig); }
5. ISO 27001 Compliance
Information Security Policy
javascript// Implement security policies const securityPolicies = { passwordPolicy: { minLength: 12, requireUppercase: true, requireLowercase: true, requireNumbers: true, requireSpecialChars: true, maxAge: 90 // days }, tokenPolicy: { accessTokenExpiry: 900, // 15 minutes refreshTokenExpiry: 604800, // 7 days maxConcurrentSessions: 5 }, sessionPolicy: { idleTimeout: 1800, // 30 minutes absoluteTimeout: 28800 // 8 hours } }; // Validate password policy function validatePassword(password) { const policy = securityPolicies.passwordPolicy; if (password.length < policy.minLength) { throw new Error('Password too short'); } if (policy.requireUppercase && !/[A-Z]/.test(password)) { throw new Error('Password must contain uppercase letters'); } // ... other validations return true; }
Risk Assessment
javascript// Implement risk assessment async function assessSecurityRisk(userId, action) { const riskFactors = { unusualLocation: await checkUnusualLocation(userId), unusualTime: await checkUnusualTime(userId), multipleFailedAttempts: await checkFailedAttempts(userId), newDevice: await checkNewDevice(userId) }; const riskScore = Object.values(riskFactors) .filter(Boolean) .length; if (riskScore >= 2) { // High risk, require additional verification return { risk: 'HIGH', requireMFA: true }; } return { risk: 'LOW', requireMFA: false }; } // Usage example app.post('/auth/login', async (req, res) => { const { username, password } = req.body; const user = await validateUser(username, password); const riskAssessment = await assessSecurityRisk(user.id, 'LOGIN'); if (riskAssessment.requireMFA) { return res.json({ requireMFA: true, mfaMethods: ['sms', 'totp'] }); } const token = generateToken(user); res.json({ token }); });
6. Compliance Checklist
GDPR Checklist
- Implement data minimization principle
- Provide right to access
- Implement right to deletion
- Obtain explicit consent
- Implement data protection measures
- Record data processing activities
- Designate Data Protection Officer (DPO)
HIPAA Checklist
- Protect PHI confidentiality
- Implement access controls
- Log all PHI access
- Implement principle of least privilege
- Conduct regular risk assessments
- Sign Business Associate Agreements (BAA)
- Train employees on security awareness
PCI DSS Checklist
- Don't store full card numbers
- Use tokenization technology
- Encrypt transmitted data
- Use strong encryption algorithms
- Regularly update keys
- Implement access controls
- Conduct regular security testing
SOC 2 Checklist
- Implement access controls
- Log all system activities
- Implement change management processes
- Conduct regular audits
- Establish incident response plan
- Conduct employee background checks
- Regular security training
ISO 27001 Checklist
- Establish information security policy
- Implement risk assessment
- Establish access controls
- Implement password policies
- Regular security audits
- Establish incident response procedures
- Continuously improve security measures
7. Best Practices
Compliance Best Practices
- Understand applicable regulations: Determine which compliance requirements apply to your business
- Implement least privilege: Only grant necessary access permissions
- Log all activities: Maintain complete audit logs
- Regular audits: Regularly check compliance
- Train employees: Ensure employees understand compliance requirements
- Use encryption: Protect sensitive data
- Implement access controls: Limit access to sensitive information
- Establish incident response: Prepare for security incidents
- Regular updates: Keep systems and policies up to date
- Seek professional advice: Consult compliance experts when necessary
By following these compliance requirements, you can ensure JWT authentication systems comply with various regulations and standards.