How to verify passwords created by Django(make_password) without Django

Question:

I have used Django and handled password with make_password and check_password.

however, I get to change a framework to fastapi.

With fastapi, I need to verify passwords that are created by Django because I should use the same database with the data.

How can I handle the passwords in the way that is compatible with Django?

Password’s format stored in database is like that 'pbkdf2_sha256$100000$Dl6Atsc1xX0A$0QFvZLpKdcvcmCNixVCdEA5gJ67yef/gkgaCKTYzoo4='

Asked By: SangminKim

||

Answers:

This document describes how Django stores passwords:

https://docs.djangoproject.com/en/2.2/topics/auth/passwords/

I do something similar to what you’re talking about with a Node.js backend. You can split on the $ character to get the pieces you need to verify a password. Here’s a snippet of what I’ve done:

const [, iterations, salt,] = hash.split('$');
const algorithm = 'pbkdf2_sha256';
salt = (salt === '') ? makeSalt() : salt;
const key = crypto.pbkdf2Sync(password, salt, iterations, 32, 'sha256');
const rtnval = algorithm + '$' + iterations + '$' + salt + '$' + key.toString('base64');

That should get you something you can use to match with the database entry for the given user.

Answered By: themanatuf

I have found passlib support Django compatible way.

from django.contrib.auth.hashers import make_password
from passlib.handlers.django import django_pbkdf2_sha256

password = 'testpassword123'
django_hash = make_password(password)   
is_verified = django_pbkdf2_sha256.verify(password, django_hash)

if is_verified:
  print('Correct!!')
Answered By: SangminKim

Further to solution from SangminKim, I would like to propose as

def authenticate_user(db, UserId: str, Password: str):
user = db.query(orm.Users).filter_by(Id= UserId).first()
if user:
if pwd_context.verify(Password, user.Password):
return user
elif django_pbkdf2_sha256.verify(Password, user.Password): # in case the password was made with django
return user
return False

**above code checks the password against FastApi proposed method & in failure case checks against django make_password as the alternative method **

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.