CodeMarine is a desktop IDE tool

Best Practices 25 min read

Secure Coding Patterns: Best Practices for AI-Assisted Development

Master essential secure coding patterns that prevent vulnerabilities in AI-generated code. From authentication to data protection, learn the patterns that keep your applications secure.

Published: September 7, 2025

πŸ›‘οΈ Why Secure Patterns Matter

AI assistants excel at generating functional code quickly, but they often miss security considerations. By mastering these secure coding patterns, you can guide AI tools toward generating secure code from the start.

85%
Fewer vulnerabilities with secure patterns
3x
Faster secure development
90%
Reduction in security debt

Authentication Patterns

Secure JWT Implementation

❌ Insecure Pattern

// AI assistant suggestion
const token = jwt.sign({userId: user.id}, 'secret');
const payload = jwt.decode(token); // No verification!
if (payload.userId) { /* authorized */ }

βœ… Secure Pattern

// Secure JWT implementation
const token = jwt.sign({userId: user.id, exp: Math.floor(Date.now() / 1000) + 3600}, process.env.JWT_SECRET, {algorithm: 'HS256'});
const payload = jwt.verify(token, process.env.JWT_SECRET, {algorithms: ['HS256']});
if (payload.userId) { /* verified and authorized */ }

πŸ”‘ JWT Security Checklist

  • β€’ Always use jwt.verify(), never jwt.decode() for authentication
  • β€’ Store secrets in environment variables, never hardcode
  • β€’ Set appropriate expiration times
  • β€’ Specify allowed algorithms explicitly
  • β€’ Include issuer and audience claims for validation

Password Security Pattern

❌ Insecure Pattern

// Plain text storage
const user = {email, password}; // Plain text!
await db.users.create(user);
if (inputPassword === user.password) { /* login */ }

βœ… Secure Pattern

// Proper hashing with salt
const bcrypt = require('bcrypt');
const saltRounds = 12;
const hashedPassword = await bcrypt.hash(password, saltRounds);
const user = {email, password: hashedPassword};
const isValid = await bcrypt.compare(inputPassword, user.password);

Input Validation Patterns

Allowlist Validation Pattern

❌ Blocklist Approach

// Trying to block bad inputs
const blocked = ['script', 'eval', 'exec'];
if (!blocked.some(b => input.includes(b))) {
processInput(input); // Still vulnerable!
}

βœ… Allowlist Approach

// Only allow known good inputs
const allowedCommands = ['list', 'show', 'get', 'view'];
const allowedFiles = ['data.txt', 'config.json'];
if (allowedCommands.includes(command) && allowedFiles.includes(file)) {
processInput(command, file); // Safe!
}

Data Protection Patterns

Encryption at Rest Pattern

❌ Plain Text Storage

// Storing sensitive data in plain text
const userData = {
ssn: '123-45-6789', // Plain text!
creditCard: '4111-1111-1111-1111'
};
await db.save(userData);

βœ… Encrypted Storage

// Encrypt sensitive data
const crypto = require('crypto');
const algorithm = 'aes-256-gcm';
const key = process.env.ENCRYPTION_KEY;
const encryptedSSN = encrypt(ssn, key);
const userData = {ssn: encryptedSSN};

Secure Error Handling

Information Disclosure Prevention

❌ Verbose Errors

// Exposing internal details
try {
await db.query(sql, params);
} catch (error) {
res.status(500).send(error.message); // Leaks info!
}

βœ… Safe Error Handling

// Generic user messages, detailed logs
try {
await db.query(sql, params);
} catch (error) {
logger.error('Database error:', error); // Log details
res.status(500).send('Internal server error'); // Generic message
}

API Security Patterns

Rate Limiting Pattern

// Express rate limiting middleware
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
message: 'Too many requests, please try again later'
});
app.use('/api/', limiter);

πŸͺ– Sarge's Security Pattern Rules

"Defense in depth beats hope in production."
"Allowlists are your armor. Blocklists are wishful thinking."
"Encrypt everything twice, trust nothing once."
"Log like your job depends on it - because it does."

Secure Coding Pattern Checklist

Authentication & Authorization

  • βœ“ Use jwt.verify() with proper validation
  • βœ“ Hash passwords with bcrypt (12+ rounds)
  • βœ“ Implement proper session management
  • βœ“ Use principle of least privilege

Input & Data Protection

  • βœ“ Implement allowlist validation
  • βœ“ Encrypt sensitive data at rest
  • βœ“ Use parameterized queries
  • βœ“ Sanitize all user inputs

Implement Secure Patterns Today

Start using these secure coding patterns in your AI-assisted development. CodeMarine helps you identify when to apply these patterns and ensures your code follows security best practices.