TL;DR
Stop storing your client authentication key directly in your code! This guide shows you how to use environment variables and a secure configuration file to manage your key safely. We’ll cover reading the key from an environment variable, using a config file, and basic security considerations.
Steps
- Understand the Problem: Hardcoding keys is bad because:
- If your code gets shared (even accidentally), the key is exposed.
- Changing the key requires modifying and redeploying your code everywhere.
- It’s a security risk!
- Use Environment Variables: Environment variables store configuration information outside of your code.
- Set an environment variable (e.g.,
CLIENT_API_KEY) on your server or development machine. The exact method depends on your operating system and hosting provider. - In your code, read the key from this variable. Here’s an example in Python:
import os client_api_key = os.environ.get('CLIENT_API_KEY') if client_api_key is None: print("Error: CLIENT_API_KEY environment variable not set!") exit(1) # Now you can use client_api_key
- Set an environment variable (e.g.,
- Use a Configuration File (Recommended): A config file is more organised than many environment variables, especially for complex setups.
- Create a configuration file (e.g.,
config.iniorconfig.json). Example using INI format:[API] client_api_key = your_secret_api_key - Load the configuration file in your code.
import configparser config = configparser.ConfigParser() config.read('config.ini') client_api_key = config['API']['client_api_key']
- Create a configuration file (e.g.,
- Security Considerations:
- Never commit your configuration file to version control (e.g., Git)! Add it to your
.gitignorefile.config.ini - Restrict access to the configuration file on your server. Only the user running your application should be able to read it (permissions: 600).
- Consider using a secrets management service (e.g., HashiCorp Vault, AWS Secrets Manager) for production environments. These services provide more advanced security features like encryption and access control.
- Never commit your configuration file to version control (e.g., Git)! Add it to your
- Testing:
- Create separate configuration files or environment variables for development and testing to avoid using your real API key in non-production environments.
- Ensure your tests read the correct keys based on the current environment.

