Search code examples
pythonflaskpasslib

Check password hash created by Django in Flask


I have a password hash generated by Django. I want to log in a user with this password hash from Flask. How can I verify the password in Flask?

from django.contrib.auth import hashers
hash = hashers.make_password('pasword')
# pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

Solution

  • You can use the passlib package to work with password hashes. It comes with support for Django's hash format. Your example hash uses pbkdf2_sha256, so use the corresponding passlib hash:

    from passlib.hash import django_pbkdf2_sha256
    hash = 'pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='
    user_input = 'password'
    django_pbkdf2_sha256.verify(user_input, hash)
    

    If you want to support multiple formats, like Django does, you can use the pre-configured Django context, or make your own with whatever order is in Django's PASSWORD_HASHERS.

    from passlib.apps import django_context
    hash = 'pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='
    user_input = 'password'
    django_context.verify(user_input, hash)