问题
While trying to write a login functionality in flask, I wanted to try 'bcrypt' flask extensio. When I use_bcrypt.check_password_hash()_ method to compare user form input password against that users saved password in the db, it always returns false.
Here is the code I use to generate passwords:
hashPwd = bcrypt.generate_password_hash('form.password.data')
Here is the code I use to check the candidate password against the saved one:
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user and bcrypt.check_password_hash(user.password, form.password.data):
login_user(user, remember=form.rememberMe.data)
If I do User.query.get(1).password
in python shell, the password is in format:
u'$2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC'
When I run the same query in code, the password is:
$2b$12$JOXUftWBbn/egABOkAYNwezGKfh6GzIHOofUnvx73AiSOfoNWEGFC
The u' in the first pw is the only difference and that might be the issue cause, but I dont know what it is.
Any ideas?
回答1:
From http://flask-bcrypt.readthedocs.io/en/latest/
pw_hash = bcrypt.generate_password_hash('hunter2')
bcrypt.check_password_hash(pw_hash, 'hunter2') # returns True
The reverse function needs to check the hash against the password, in your case user.password should actually be hashPwd
if user and bcrypt.check_password_hash(hashPwd, form.password.data):
来源:https://stackoverflow.com/questions/50991261/flask-bcrypt-check-password-hash-always-returns-false-cant-narrow-in-on-my-m