WordPress API Key Management: Security Best Practices
Learn how to securely store, rotate, and manage API keys in WordPress to prevent credential exposure.
API keys connect your WordPress site to payment processors, email services, analytics, and more. Poor key management can lead to service abuse, data breaches, and financial losses.
Types of API Keys in WordPress
Common Integrations
- Payment gateways (Stripe, PayPal)
- Email services (SendGrid, Mailchimp)
- Analytics (Google Analytics)
- CDN services (Cloudflare)
- Social media APIs
- Maps and geolocation services
Secure Storage Methods
wp-config.php Constants
// Store API keys as constants
define('STRIPE_SECRET_KEY', 'sk_live_...');
define('SENDGRID_API_KEY', 'SG.xxx...');
// Never store in database or theme files
Environment Variables
// Better: Use environment variables
define('STRIPE_SECRET_KEY', getenv('STRIPE_SECRET'));
// Set in server configuration or .env file
// Never commit .env to version control
WordPress Options (Encrypted)
// If using database, encrypt first
function wpfs_store_api_key($key, $value) {
$encrypted = wpfs_encrypt($value);
update_option('wpfs_api_' . $key, $encrypted);
}
function wpfs_get_api_key($key) {
$encrypted = get_option('wpfs_api_' . $key);
return wpfs_decrypt($encrypted);
}
Key Rotation Strategy
Rotation Schedule
- Rotate keys every 90 days minimum
- Immediate rotation if compromise suspected
- Rotate when team members leave
- After security incidents
Rotation Process
- Generate new key from service provider
- Update key in secure storage
- Verify functionality with new key
- Revoke old key
- Document rotation date
Access Control
Principle of Least Privilege
- Use read-only keys when possible
- Create separate keys for different functions
- Limit key permissions to required scope
- Use test keys in development
Key Scoping Example
// Stripe example: restricted key permissions
// Create key with only required permissions:
// - Read charges
// - Create refunds
// Not: full account access
Monitoring and Auditing
Track Key Usage
- Monitor API call volumes
- Alert on unusual patterns
- Review access logs regularly
- Track key usage by service
Emergency Procedures
Compromised Key Response
- Immediately revoke the compromised key
- Generate replacement key
- Update all systems using the key
- Review logs for unauthorized usage
- Notify affected users if necessary
- Document incident
Common Mistakes to Avoid
- Committing keys to Git repositories
- Storing keys in database unencrypted
- Using production keys in development
- Sharing keys via email or chat
- Never rotating keys
- Using one key for multiple purposes
Conclusion
Proper API key management protects your integrations and prevents service abuse. Store keys securely, rotate regularly, and monitor usage to maintain secure connections.
Written by Sarah Chen
WP Folder Shield Team