Flask bcrypt.check_password_hash() always returns False, can't narrow in on my mistake

大憨熊 提交于 2020-07-09 05:35:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!