Flask uses a secret key for securely signing session cookies and protecting against CSRF attacks. Without a strong secret key, your Flask application's sessions can be tampered with.
What is Flask SECRET_KEY?
The Flask SECRET_KEY is used by the framework to sign session cookies cryptographically. This signature ensures that session data cannot be modified by users. It's also used by Flask-WTF for CSRF token generation.
Key Requirements
- Should be random and unpredictable
- At least 24 characters recommended
- Can include any printable characters
- Must be consistent across application restarts
How to Use
Set the secret key in your Flask application:
```python
import os
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
# Or using a config file
app.config.from_envvar('APP_SETTINGS')
```Best Practices
- Use environment variables for the secret key
- Never use the default or example keys in production
- Use Flask-Talisman for additional security headers
- Enable secure cookies in production
- Consider using Flask-Session for server-side sessions
Common Mistakes to Avoid
- โUsing 'dev' or simple strings as secret keys
- โCommitting the secret key to version control
- โNot setting SESSION_COOKIE_SECURE in production
- โRegenerating the key and invalidating all sessions