Merge pull request #2399 from davidism/docs-secret-key
Before adoption: this commit came in with the history the project adopted, so no landing records it.
clean up secret key docs
authored by David Lord · committed by GitHub · parents 641fdea, 465922e · Browse files · 15 files·+41 added−79 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+41 added−79 removed
- tests:+12 added−47 removed
- other:+29 added−32 removed
Provenance
- Commit
d13e41d- Tree
18c5949- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
641fdea- Parent 2
465922e
15 files changed+41 added−79 removed
modified:docs/patterns/flashing.rst+1 added-1 removed
20 unmodified lines21 from flask import Flask, flash, redirect, render_template, \22 request, url_for23 24 app = Flask(__name__)25- app.secret_key = 'some_secret'25+ app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'26 27 @app.route('/')28 def index():29 return render_template('index.html')121 unmodified linesmodified:docs/tutorial/setup.rst+4 added-4 removed
31 unmodified lines32 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py34 35 # Load default config and override config from an environment variable36- app.config.update(dict(36+ app.config.update(37 DATABASE=os.path.join(app.root_path, 'flaskr.db'),38- SECRET_KEY='development key',38+ SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',39 USERNAME='admin',40 PASSWORD='default'41- ))41+ )42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)43 44 In the above code, the :class:`~flask.Config` object works similarly to a45 dictionary, so it can be updated with new values.30 unmodified lines76 method on the config object and provide it with an import name of a77 module. Flask will then initialize the variable from that module. Note78 that in all cases, only variable names that are uppercase are considered.79 80-The ``SECRET_KEY`` is needed to keep the client-side sessions secure.80+The :data:`SECRET_KEY` is needed to keep the client-side sessions secure.81 Choose that key wisely and as hard to guess and complex as possible.82 83 Lastly, add a method that allows for easy connections to the specified84 database. ::17 unmodified linesmodified:docs/api.rst+6 added-6 removed
101 unmodified lines102 103 Sessions104 --------105 106-If you have the :attr:`Flask.secret_key` set you can use sessions in Flask107-applications. A session basically makes it possible to remember108-information from one request to another. The way Flask does this is by109-using a signed cookie. So the user can look at the session contents, but110-not modify it unless they know the secret key, so make sure to set that111-to something complex and unguessable.106+If you have set :attr:`Flask.secret_key` (or configured it from107+:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes108+it possible to remember information from one request to another. The way Flask109+does this is by using a signed cookie. The user can look at the session110+contents, but can't modify it unless they know the secret key, so make sure to111+set that to something complex and unguessable.112 113 To access the current session you can use the :class:`session` object:114 115 .. class:: session711 unmodified linesmodified:docs/config.rst+4 added-4 removed
37 unmodified lines38 method::39 40 app.config.update(41 DEBUG=True,42- SECRET_KEY='...'42+ SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'43 )44 45 .. admonition:: Debug Mode with the ``flask`` Script46 319 unmodified lines366 Here is an example of a configuration file::367 368 # Example configuration369 DEBUG = False370- SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'370+ SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'371 372 Make sure to load the configuration very early on, so that extensions have373 the ability to access the configuration when starting up. There are other374 methods on the config object as well to load from individual files. For a9 unmodified lines384 385 Environment variables can be set on Linux or OS X with the export command in386 the shell before starting the server::387 388- $ export SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'388+ $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'389 $ export DEBUG=False390 $ python run-app.py391 * Running on http://127.0.0.1:5000/392 * Restarting with reloader...393 394 On Windows systems use the `set` builtin instead::395 396- >set SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'396+ >set SECRET_KEY='5f352379324c22463451387a0aec5d2f'397 >set DEBUG=False398 399 While this approach is straightforward to use, it is important to remember that400 environment variables are strings -- they are not automatically deserialized197 unmodified linesmodified:docs/quickstart.rst+10 added-13 removed
158 unmodified lines159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162 163-More information on using the debugger can be found in the `Werkzeug 163+More information on using the debugger can be found in the `Werkzeug164 documentation`_.165 166 .. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167 555 unmodified lines723 from flask import Flask, session, redirect, url_for, escape, request724 725 app = Flask(__name__)726 727+ # Set the secret key to some random bytes. Keep this really secret!728+ app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'729+730 @app.route('/')731 def index():732 if 'username' in session:733 return 'Logged in as %s' % escape(session['username'])16 unmodified lines750 # remove the username from the session if it's there751 session.pop('username', None)752 return redirect(url_for('index'))753 751- # set the secret key. keep this really secret:752- app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'753-754 The :func:`~flask.escape` mentioned here does escaping for you if you are755 not using the template engine (as in this example).756 757 .. admonition:: How to generate good secret keys758 759- The problem with random is that it's hard to judge what is truly random. And760- a secret key should be as random as possible. Your operating system761- has ways to generate pretty random stuff based on a cryptographic762- random generator which can be used to get such a key::759+ A secret key should be as random as possible. Your operating system has760+ ways to generate pretty random data based on a cryptographic random761+ generator. Use the following command to quickly generate a value for762+ :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::763 764- >>> import os765- >>> os.urandom(24)766- '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'764+ $ python -c 'import os; print(os.urandom(16))'765+ b'_5#y2L"F4Q8z\n\xec]/'766 768- Just take that thing and copy/paste it into your code and you're done.769-767 A note on cookie-based sessions: Flask will take the values you put into the768 session object and serialize them into a cookie. If you are finding some769 values do not persist across requests, cookies are indeed enabled, and you are770 not getting a clear error message, check the size of the cookie in your page76 unmodified linesmodified:examples/flaskr/flaskr/factory.py+1 added-1 removed
20 unmodified lines21 22 app.config.update(dict(23 DATABASE=os.path.join(app.root_path, 'flaskr.db'),24 DEBUG=True,25- SECRET_KEY='development key',25+ SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',26 USERNAME='admin',27 PASSWORD='default'28 ))29 app.config.update(config or {})35 unmodified linesmodified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
20 unmodified lines21 # configuration22 DATABASE = '/tmp/minitwit.db'23 PER_PAGE = 3024 DEBUG = True25-SECRET_KEY = 'development key'25+SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'26 27 # create our little application :)28 app = Flask('minitwit')29 app.config.from_object(__name__)227 unmodified linesmodified:flask/app.py+2 added-2 removed
219 unmodified lines220 #: ``TESTING`` configuration key. Defaults to ``False``.221 testing = ConfigAttribute('TESTING')222 223 #: If a secret key is set, cryptographic components can use this to224- #: sign cookies and other things. Set this to a complex random value224+ #: sign cookies and other things. Set this to a complex random value225 #: when you want to use the secure cookie for instance.226 #:227 #: This attribute can also be configured from the config with the228- #: ``SECRET_KEY`` configuration key. Defaults to ``None``.228+ #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.229 secret_key = ConfigAttribute('SECRET_KEY')230 231 #: The secure cookie uses this for the name of the session cookie.232 #:1951 unmodified linesmodified:tests/static/config.json+1 added-1 removed
1 {2 "TEST_KEY": "foo",3- "SECRET_KEY": "devkey"3+ "SECRET_KEY": "config"4 }modified:tests/conftest.py+1 added-6 removed
16 unmodified lines17 18 19 class Flask(_Flask):20 testing = True21- secret_key = __name__21+ secret_key = 'test key'22 23- def make_response(self, rv):24- if rv is None:25- rv = ''26- return super(Flask, self).make_response(rv)23 28-24 @pytest.fixture25 def app():26 app = Flask(__name__)27 return app141 unmodified linesmodified:tests/test_basic.py+2 added-22 removed
218 unmodified lines219 assert client.get('/foo/bar').data == b'bar'220 221 222 def test_session(app, client):223- app.secret_key = 'testkey'224-223 @app.route('/set', methods=['POST'])224 def set():225 flask.session['value'] = flask.request.form['value']226 return 'value set'7 unmodified lines234 235 236 def test_session_using_server_name(app, client):237 app.config.update(240- SECRET_KEY='foo',238 SERVER_NAME='example.com'239 )240 241 @app.route('/')7 unmodified lines249 250 251 def test_session_using_server_name_and_port(app, client):252 app.config.update(256- SECRET_KEY='foo',253 SERVER_NAME='example.com:8080'254 )255 256 @app.route('/')7 unmodified lines264 265 266 def test_session_using_server_name_port_and_path(app, client):267 app.config.update(272- SECRET_KEY='foo',268 SERVER_NAME='example.com:8080',269 APPLICATION_ROOT='/foo'270 )271 19 unmodified lines291 return self.app(environ, start_response)292 293 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')294 app.config.update(300- SECRET_KEY='foo',295 APPLICATION_ROOT='/bar'296 )297 298 @app.route('/')6 unmodified lines305 306 307 def test_session_using_session_settings(app, client):308 app.config.update(315- SECRET_KEY='foo',309 SERVER_NAME='www.example.com:8080',310 APPLICATION_ROOT='/test',311 SESSION_COOKIE_DOMAIN='.example.com',312 SESSION_COOKIE_HTTPONLY=False,15 unmodified lines328 329 330 def test_session_localhost_warning(recwarn, app, client):331 app.config.update(339- SECRET_KEY='testing',332 SERVER_NAME='localhost:5000',333 )334 335 @app.route('/')8 unmodified lines344 345 346 def test_session_ip_warning(recwarn, app, client):347 app.config.update(356- SECRET_KEY='testing',348 SERVER_NAME='127.0.0.1:5000',349 )350 351 @app.route('/')6 unmodified lines358 w = recwarn.pop(UserWarning)359 assert 'cookie domain is an IP' in str(w.message)360 361 371-def test_missing_session():372- app = flask.Flask(__name__)362+def test_missing_session(app):363+ app.secret_key = None364 365 def expect_exception(f, *args, **kwargs):366 e = pytest.raises(RuntimeError, f, *args, **kwargs)367 assert e.value.args and 'session is unavailable' in e.value.args[0]5 unmodified lines373 374 375 def test_session_expiration(app, client):376 permanent = True386- app.secret_key = 'testkey'377 378 @app.route('/')379 def index():380 flask.session['test'] = 4223 unmodified lines404 assert match is None405 406 407 def test_session_stored_last(app, client):418- app.secret_key = 'development-key'419-408 @app.after_request409 def modify_session(response):410 flask.session['foo'] = 42411 return response6 unmodified lines418 assert client.get('/').data == b'42'419 420 421 def test_session_special_types(app, client):434- app.secret_key = 'development-key'422 now = datetime.utcnow().replace(microsecond=0)423 the_uuid = uuid.uuid4()424 425 @app.route('/')23 unmodified lines449 assert s['di_tag'] == {' di': 'not-a-dict'}450 451 452 def test_session_cookie_setting(app):466- app.secret_key = 'dev key'453 is_permanent = True454 455 @app.route('/bump')456 def bump():33 unmodified lines490 run_test(expect_header=False)491 492 493 def test_session_vary_cookie(app, client):508- app.secret_key = 'testkey'509-494 @app.route('/set')495 def set_session():496 flask.session['test'] = 'test'497 return ''47 unmodified lines545 expect('/no-vary-header', None)546 547 548 def test_flashes(app, req_ctx):565- app.secret_key = 'testkey'566-549 assert not flask.session.modified550 flask.flash('Zap')551 flask.session.modified = False552 flask.flash('Zip')7 unmodified lines560 # Specifically, if app.testing is not set to True, the AssertionErrors561 # in the view functions will cause a 500 response to the test client562 # instead of propagating exceptions.563 582- app.secret_key = 'testkey'583-564 @app.route('/')565 def index():566 flask.flash(u'Hello World')567 flask.flash(u'Hello World', 'error')1265 unmodified linesmodified:tests/test_config.py+7 added-6 removed
17 unmodified lines18 19 20 # config keys used for the TestConfig21 TEST_KEY = 'foo'22-SECRET_KEY = 'devkey'22+SECRET_KEY = 'config'23 24 25 def common_object_test(app):26- assert app.secret_key == 'devkey'26+ assert app.secret_key == 'config'27 assert app.config['TEST_KEY'] == 'foo'28 assert 'TestConfig' not in app.config29 30 18 unmodified lines49 50 def test_config_from_mapping():51 app = flask.Flask(__name__)52 app.config.from_mapping({53- 'SECRET_KEY': 'devkey',53+ 'SECRET_KEY': 'config',54 'TEST_KEY': 'foo'55 })56 common_object_test(app)57 58 app = flask.Flask(__name__)59 app.config.from_mapping([60- ('SECRET_KEY', 'devkey'),60+ ('SECRET_KEY', 'config'),61 ('TEST_KEY', 'foo')62 ])63 common_object_test(app)64 65 app = flask.Flask(__name__)66 app.config.from_mapping(67- SECRET_KEY='devkey',67+ SECRET_KEY='config',68 TEST_KEY='foo'69 )70 common_object_test(app)71 8 unmodified lines80 class Base(object):81 TEST_KEY = 'foo'82 83 class Test(Base):84- SECRET_KEY = 'devkey'84+ SECRET_KEY = 'config'85+86 app = flask.Flask(__name__)87 app.config.from_object(Test)88 common_object_test(app)89 119 unmodified linesmodified:tests/test_signals.py+1 added-4 removed
155 unmodified lines156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158 159 160-def test_flash_signal():161- app = flask.Flask(__name__)162- app.config['SECRET_KEY'] = 'secret'163-160+def test_flash_signal(app):161 @app.route('/')162 def index():163 flask.flash('This is a flash message', category='notice')164 return flask.redirect('/other')39 unmodified linesmodified:tests/test_templating.py-2 removed
50 unmodified lines51 assert rv == 'Hello Special World 42'52 53 54 def test_standard_context(app, client):55- app.secret_key = 'development key'56-55 @app.route('/')56 def index():57 flask.g.foo = 2358 flask.session['test'] = 'aha'389 unmodified linesmodified:tests/test_testing.py-6 removed
105 unmodified lines106 assert rv.data == b'http://xxx.example.com:1234/foo/'107 108 109 def test_redirect_keep_session(app, client, app_ctx):110- app.secret_key = 'testing'111-110 @app.route('/', methods=['GET', 'POST'])111 def index():112 if flask.request.method == 'POST':113 return flask.redirect('/getsession')22 unmodified lines136 assert rv.data == b'foo'137 138 139 def test_session_transactions(app, client):142- app.secret_key = 'testing'143-140 @app.route('/')141 def index():142 return text_type(flask.session['foo'])143 20 unmodified lines164 assert 'Session backend did not open a session' in str(e.value)165 166 167 def test_session_transactions_keep_context(app, client, req_ctx):172- app.secret_key = 'testing'173-168 rv = client.get('/')169 req = flask.request._get_current_object()170 assert req is not None171 with client.session_transaction():140 unmodified lines