简体   繁体   English

如何在使用Flask邮件时保持邮件密码的安全

[英]How to keep mail password safe while using flask mail

I am using flask mail to send messages from app. 我正在使用烧瓶邮件从应用程序发送消息。 I am doing something like this: 我正在做这样的事情:

app = Flask(__name__)
app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME = 'your@gmail.com',
    MAIL_PASSWORD = 'yourpassword'
    )
mail = Mail(app)

But I don't want my password be visible in my code. 但是我不希望密码在我的代码中可见。 I want to encrypt it, for example. 例如,我想对其进行加密。 I can store in database but I still doesn't get how to keep it encrypted because I need to decrypt it to set MAIL_PASSWORD property. 我可以存储在数据库中,但仍然无法获得加密方法,因为我需要解密它才能设置MAIL_PASSWORD属性。

Your app must be able to access your cleartext password, so encrypting it is useless in the scenario where the server gets compromised. 您的应用必须能够访问您的明文密码,因此在服务器受到威胁的情况下,对其进行加密是没有用的。

Encryption may be useful (but I don't suggest it) if you want to save it on a public place (eg code on github) and then you give the key only to the application (for example with a non tracked file or in a environment variable). 如果您想将其保存在公共场所(例如,github上的代码),然后仅将密钥提供给应用程序(例如,使用非跟踪文件或在应用程序中),则加密可能很有用(但我不建议这样做)。环境变量)。

Since you must give your application some secret, I suggest you to simply give the email password as a secret. 由于您必须为您的应用程序提供一些秘密,因此建议您仅将电子邮件密码作为秘密。

For example using a file called local_settings.py you can do this: 例如,使用名为local_settings.py的文件,您可以这样做:

# local_settings.py
MAIL_PASSWORD = 'mypassword'

# app.py
...
import local_settings

app = Flask(__name__)
app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME = 'your@gmail.com',
    MAIL_PASSWORD = local_settings.MAIL_PASSWORD
    )
mail = Mail(app)

Using environment variable is a good option (for mail password, database password, ...). 使用环境变量是一个不错的选择(用于邮件密码,数据库密码等)。 Example: 例:

import os
app = Flask(__name__)
app.config.update(
    MAIL_SERVER='smtp.gmail.com',
    MAIL_PORT=465,
    MAIL_USE_SSL=True,
    MAIL_USERNAME = 'your@gmail.com',
    MAIL_PASSWORD = os.environ['MAIL_PASSWORD']
    )
mail = Mail(app)

You can set value for MAIL_PASSWORD environment variable every time run script, using 您可以在每次运行脚本时使用以下MAIL_PASSWORDMAIL_PASSWORD环境变量设置值:

  1. In Linux: export MAIL_PASSWORD="{your_mail_password}" 在Linux中: export MAIL_PASSWORD="{your_mail_password}"
  2. In Windows: set MAIL_PASSWORD="{your_mail_password}" 在Windows中: set MAIL_PASSWORD="{your_mail_password}"

Shouldn't use plain text in file to store password 不应在文件中使用纯文本存储密码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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