python passlib 验证不匹配

python passlib verify doesn't match

我正在使用 Flask 和 MongoDB,尝试使用 passlib 实现用户名/密码验证。

来自 models.py 的 class :

from passlib.hash import sha256_crypt

class Users(object):
    def __init__(self, username='', password='', collection=db.users, articles=''):
    self.collection = collection
    self.username = username
    self.password = password
    self.articles = []

def addUser(self):
    self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt('self.password'), 'articles': self.articles})

从 python shell,我创建了用户 alice,密码为 'secret' :

>>> import models
>>> alice = models.Users()
>>> alice.username = 'alice'
>>> alice.password = 'secret'
>>> alice.addUser()

从 mongo shell,我检查文档是否使用哈希而不是明文密码正确创建:

> db.users.find()
{ "_id" : ObjectId("57f15d9f815a0b6c1533427f"), "username" : "alice", "articles" : [ ], "password" : "$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7" }

从现在开始,我们应该能够使用存储在文档中的散列来验证来自 python shell 的密码,不是吗?

>>> sha256_crypt.verify('secret','$rounds=535000$Oq1hy1INzO59nu0q$FzMz1DtBWDwM.sw0AhrlVA8esgE30n8rr/NjOltB8.7')
False

但是没有,有人可以向我解释为什么吗?

发生这种情况是因为您加密的不是 self.password 而是 'self.password'

因此您需要将 addUser 方法更改为以下内容:

def addUser(self):
    self.collection.insert({'username': self.username, 'password': sha256_crypt.encrypt(self.password), 'articles': self.articles})