Session data corrupted in django

10,934

Solution 1

Sorry for getting late to this post, but by any chance, did you change the SECRET_KEY variable on your project? sessions used to be cyphered using this salt, so if you changed it you have corrupted all your sessions, but don't worry! is not a big deal, the worst-case scenario is for the sessions that were existing before this, those will need to log-in again, and that's it ;)

Solution 2

You are getting this error because of this line: https://github.com/django/django/blob/master/django/contrib/sessions/backends/base.py#L109

Apparently, there's something went terribly wrong with encryption of session data.

How to fix it? I'm not sure, I have a couple of ideas though:

  • Do you use a custom session class?
  • Do you use your Django session in another project?

Solution 3

This worked for me:

import base64
import hashlib
import hmac
import json

def session_utoken(msg, secret_key, class_name='SessionStore'):
    key_salt = "django.contrib.sessions" + class_name
    sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
    utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
    return utoken


def decode(session_data, secret_key, class_name='SessionStore'):
    encoded_data = base64.b64decode(session_data)
    utoken, pickled = encoded_data.split(b':', 1)
    expected_utoken = session_utoken(pickled, secret_key, class_name)
    if utoken.decode() != expected_utoken:
        raise BaseException('Session data corrupted "%s" != "%s"',
                            utoken.decode(),
                            expected_utoken)
    return json.loads(pickled.decode('utf-8'))

s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))

credit to: http://joelinoff.com/blog/?p=920

Solution 4

Sometimes this problem could be raised when you open two different projects at same runtime. So first stop your server, close completely and exist Now open ur server again and start ur current project on new fresher runtime

Share:
10,934

Related videos on Youtube

gjivanya
Author by

gjivanya

Updated on June 06, 2022

Comments

  • gjivanya
    gjivanya about 2 years

    Every time when I'm going to my signup page, I'm receiving this error

    Session data corrupted
    

    when I'm trying to signup anyway, POST request status is 302, but User is still created, but didn't save any email to registered user.

    Why I'm getting that error and how can I fix it?

    Thanks!

  • Ibrahim Tayseer
    Ibrahim Tayseer almost 5 years
    make sure that your is not randomly like this SECRET_KEY = get_random_string(50, chars)
  • Gervasius Twinklewinkleson
    Gervasius Twinklewinkleson over 3 years
    how are you suppose to use this? do this functions belong in a middleware or something else? the link page is empty
  • ruslaniv
    ruslaniv about 3 years
    Also worth clearing all existing cookies for your Django site to stop seeing this message.