每次启动Flask应用程序时,为什么不生成密钥? [英] Why not generating the secret key every time Flask application starts?

查看:164
本文介绍了每次启动Flask应用程序时,为什么不生成密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用会话时,Flask需要一个密钥。在我见过的每一个例子中,秘密密钥都是以某种方式生成的,然后存储在源代码或配置文件中。



永久存储它的原因是什么?为什么不在Flask应用程序启动时简单生成它?

  app.secret_key = os.urandom(50)

code>

我只能想象出两种情况,这是一个问题:


  1. 在使用同一用户可能从服务器移动到服务器的情况下(因为多台计算机将生成不同的密钥)的故障转移变体,

  2. 使用积极的持续交付:每天交付几十次,突破每个用户的交易将很快成为第一个问题。

  3. >

    是否还有其他情况?

    解决方案

    密钥用于签名会话cookie。如果您必须重新启动应用程序并重新生成密钥,则所有现有会话都将失效。这可能不是你想要的(或者至少,不是正确的方法去关于无效的会议)。类似的情况下,可以为任何其他依赖于密钥,如由其危险产生的令牌提供重置密码URL(例如)。

    标准做法是有一些不必要的钥匙交给回购(所以这里有一些开发机器的东西),然后在部署时在本地配置中设置密钥。这样,密钥不会泄漏,也不需要重新生成。

    还有一种情况是运行依赖于应用上下文的辅助系统,比如芹菜运行后台任务。如果应用程序的每个正在运行的实例具有不同的设置,则在某些情况下可能无法正确协同工作。


    When using sessions, Flask requires a secret key. In every example I've seen, the secret key is somehow generated and then stored either in source code or in configuration file.

    What is the reason to store it permanently? Why not simply generating it when Flask application starts?

    app.secret_key = os.urandom(50)
    

    I can only imagine two cases where this would be a problem:

    1. When using a variant of a failover where the same user may be moved from server to server (since several machines will generate different keys),

    2. When using aggressive continuous delivery: with several dozens of deliveries per day, breaking the sessions of every user would quickly become the issue number one.

    Are there any other cases?

    解决方案

    The secret key is used to sign the session cookie. If you had to restart your application, and regenerated the key, all the existing sessions would be invalidated. That's probably not what you want (or at least, not the right way to go about invalidating sessions). A similar case could be made for anything else that relies on the secret key, such as tokens generated by itsdangerous to provide reset password urls (for example).

    The standard practice is to have some throwaway key commited to the repo (so that there's something there for dev machines) and then to set the key in the local config when deploying. This way, the key isn't leaked and doesn't need to be regenerated.

    There's also the case of running secondary systems that depend on the app context, such as Celery for running background tasks. If each running instance of the application has different settings, they may not work together correctly in some cases.

    这篇关于每次启动Flask应用程序时,为什么不生成密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆