简体   繁体   中英

Safe way to store mysql server credentials in flask?

I was wondering about the safety of some thing in my app.py flask app. First the database, I'm using mysql and currently I am connecting to it in the following way:

# Config MySQL
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'databasename'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

And to me this feels very weird, just putting in your password in plain text etc. I've been searching online but have not found any other way of doing this other than putting it in a seperate python file and just importing it. Which kinda feels like doing nothing at all.. Is there a better way to do this security wise?

Then the secret key I use for password encoding. Which is also just stored in plain text in my code, is there also a way to make this more secure or make it less obvious?

Thanks in advance!

The computer which runs your code needs to know the password, so you can't secure against the owner of the computer (if that's not you). But if you are having the password in the sourcecode it can easily happen that you put it into version control and if you use a public github it can easily happen that you publish your key.

As alternative you can put the password in a config file (take care to not put it into version control eg via .gitignore ) or you can use environmental variables.

I would suggest to store the credentials in the OS environment.

app.config['MYSQL_HOST'] = os.environ.get('HOST')
app.config['MYSQL_USER'] = os.environ.get('USER')
app.config['MYSQL_PASSWORD'] = os.environ.get('PASSWORD')
app.config['MYSQL_DB'] = os.environ.get('DB')
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'

It will help you to get those information from a standalone application or as a dockerized application (using docker file).

Another way is .env file

pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()

class Config:
   SECRET_KEY = os.getenv("SECRET_KEY")

Remember to gitignore .env as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM