简体   繁体   English

Django:会话在Heroku上没有按预期工作

[英]Django: Sessions not working as expected on Heroku

Users keep getting logged out and sessions are not persisting on my Django app on Heroku. 用户不断登出,并且会话不会在Heroku上的Django应用程序上持续存在。 Users can log in, but they will be randomly logged out—even on the /admin/ site. 用户可以登录,但他们将被随机注销 - 甚至在/admin/ site上。

Is there anything I'm doing wrong with my Django/Heroku config? 我的Django / Heroku配置有什么问题吗?

Currently running Django 1.11.16 on Standard Dynos. 目前在Standard Dynos上运行Django 1.11.16。

settings.py settings.py

SECRET_KEY = os.environ.get("SECRET_KEY", "".join(random.choice(string.printable) for i in range(40)))

SESSION_COOKIE_DOMAIN = ".appname.com"
CSRF_COOKIE_DOMAIN = ".appname.com"

SECURE_SSL_REDIRECT = True

# ...

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates/')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.template.context_processors.csrf',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# ...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'appname',
    }
}

# https://devcenter.heroku.com/articles/python-concurrency-and-database-connections
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

The problem was that SECRET_KEY was not static on Heroku. 问题是SECRET_KEY在Heroku上不是静态的。 The SECRET_KEY changing was breaking sessions. SECRET_KEY变化打破了会议。 The fix is to add a static SECRET_KEY to Heroku config: 修复是向Heroku配置添加静态SECRET_KEY

heroku config:set SECRET_KEY=`openssl rand -base64 32`

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

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