Claude Code has broad access to your filesystem and can execute commands, making security configuration essential. This guide covers protecting sensitive data like API keys and credentials, configuring appropriate permission boundaries, auditing AI-generated code for vulnerabilities, and using hooks to enforce security policies automatically. Follow these practices to harness Claude Code's power without compromising your project's security posture.
securitysecretspermissionsaudithooks
Protecting Secrets and Credentials
The first rule of using Claude Code securely is ensuring that secrets never enter the conversation context. API keys, database passwords, authentication tokens, and other credentials should be stored in .env files that are excluded from Claude's reach. Add .env and similar files to your .claudeignore to prevent accidental reads.
Beyond file-level exclusion, be mindful of secrets that might appear in unexpected places: hardcoded values in configuration files, credentials in docker-compose.yml, tokens in CI configuration, or passwords in database seed files. A comprehensive .claudeignore should cover all these patterns.
When Claude needs to work with services that require authentication, use environment variable references rather than actual values. Instruct Claude to write code that reads from process.env rather than embedding credentials. Add this as an explicit rule in your CLAUDE.md so Claude never suggests inline secrets.
# .claudeignore - exclude all secret-containing files
.env
.env.*
*.pem
*.key
credentials.json
service-account.json
docker-compose.override.yml
# CLAUDE.md security section
# Security Rules
- NEVER read or output .env file contents
- NEVER hardcode API keys, tokens, or passwords
- Always use environment variables: process.env.API_KEY
- Never log sensitive data (tokens, passwords, PII)
- Use parameterized queries for all database operations
Permission Boundaries
Claude Code can read files, write files, and execute shell commands. Configuring appropriate boundaries for these capabilities is crucial. Use the permission system to restrict which directories Claude can modify and which commands it can execute without approval.
For most projects, a sensible default is to allow reads broadly but restrict writes to source directories only. Prevent writes to configuration files, CI pipelines, and infrastructure code unless explicitly approved. This prevents accidental changes to critical operational files during routine coding tasks.
For shell command execution, maintain an allowlist of safe commands. Build tools, test runners, and linters are generally safe. Commands that modify system configuration, access the network, or manage infrastructure should require explicit confirmation. This layered approach lets Claude be productive while maintaining human oversight for high-impact operations.
# Configure permission boundaries in settings
# Allow file reads everywhere except secrets
claude config set permissions.read "src/**,tests/**,docs/**"
# Restrict writes to source code only
claude config set permissions.write "src/**,tests/**"
# Safe commands that can run without confirmation
claude config set permissions.allowedCommands \
"npm test,npm run lint,npm run build,npx tsc --noEmit"
# Commands that always require confirmation
# (default behavior for destructive operations)
# rm, git push, docker, kubectl, etc.
Auditing AI-Generated Code
AI-generated code can introduce subtle security vulnerabilities that are easy to miss in review. Common issues include insufficient input validation, improper error handling that leaks internal details, SQL injection through string concatenation, and missing authentication checks on new endpoints.
Establish an audit checklist specifically for AI-generated code. Check that all user inputs are validated and sanitized, that error messages do not expose stack traces or internal paths, that database queries use parameterized statements, and that new API endpoints include proper authentication and authorization middleware.
Automate what you can. Run static analysis tools like ESLint security plugins, Semgrep, or Snyk on every PR that includes AI-generated code. Add these checks to your CI pipeline so they catch common vulnerability patterns before code reaches production. Claude Code can even help set up these checks as part of your security workflow.
# Add security-focused ESLint rules
npm install --save-dev eslint-plugin-security
# .eslintrc.js
module.exports = {
plugins: ['security'],
rules: {
'security/detect-object-injection': 'warn',
'security/detect-non-literal-regexp': 'warn',
'security/detect-unsafe-regex': 'error',
'security/detect-eval-with-expression': 'error',
'security/detect-no-csrf-before-method-override': 'error',
}
};
# Run security audit as part of CI
npx semgrep --config=p/javascript-security src/
Security Hooks and Automation
Claude Code hooks let you run custom scripts before or after specific events, making them perfect for automated security enforcement. A PreToolUse hook can inspect commands before execution, blocking dangerous operations. A PostToolUse hook can scan generated code for security issues immediately after creation.
A practical PreToolUse hook checks shell commands against a blocklist of dangerous patterns: commands that delete files outside the project, commands that access network resources without approval, or commands that modify system configuration. This acts as a safety net even if permission boundaries are misconfigured.
Combine hooks with your CLAUDE.md security rules for defense in depth. The CLAUDE.md tells Claude what it should do, while hooks enforce what it must do. This dual-layer approach ensures security even when prompts are ambiguous or when Claude misinterprets instructions.
# .claude/hooks/pre-command.sh
#!/bin/bash
# Block dangerous command patterns
BLOCKED_PATTERNS=(
"rm -rf /"
"curl.*|.*sh"
"chmod 777"
"git push.*--force.*main"
"DROP TABLE"
"DROP DATABASE"
)
for pattern in "${BLOCKED_PATTERNS[@]}"; do
if echo "$1" | grep -qE "$pattern"; then
echo "BLOCKED: Command matches dangerous pattern: $pattern"
exit 1
fi
done
exit 0
# Register the hook
# claude config add hooks.PreToolUse ".claude/hooks/pre-command.sh"
Terminal Preview
Security Best Practices
About Security Best Practices
Claude Code guides provide in-depth, step-by-step instructions for mastering specific aspects of Claude Code. Security Best Practices is a Intermediate-level guide that walks you through best practices, real-world techniques, and practical tips to help you get the most out of Claude Code in your daily workflow.