我正在創建一個網站上創建一個「創建用戶」路由,後面跟着一個「登錄」路由。Python Flask用戶用加密登錄
我需要密碼從創建用戶是加密(路線是一個POST方法,以「用戶名」,「密碼」等的變量名...
我需要加密密碼,用戶名和變量的其餘部分是我正在
我需要登錄路由,以確認正確的憑據在服務器上插入到數據庫我知道如何檢查用戶名,但我似乎無法弄清楚如何驗證存儲在數據庫中的加密密碼
我已經嘗試了幾個在線示例,但其中大多數只是創建靜態用戶,我似乎無法複製它爲我的數據庫。 任何幫助,將不勝感激。
我正在創建一個網站上創建一個「創建用戶」路由,後面跟着一個「登錄」路由。Python Flask用戶用加密登錄
我需要密碼從創建用戶是加密(路線是一個POST方法,以「用戶名」,「密碼」等的變量名...
我需要加密密碼,用戶名和變量的其餘部分是我正在
我需要登錄路由,以確認正確的憑據在服務器上插入到數據庫我知道如何檢查用戶名,但我似乎無法弄清楚如何驗證存儲在數據庫中的加密密碼
我已經嘗試了幾個在線示例,但其中大多數只是創建靜態用戶,我似乎無法複製它爲我的數據庫。 任何幫助,將不勝感激。
雖然
任何幫助,將不勝感激。
是不是真的一個問題,我假設你想知道如何安全地存儲密碼並檢查存儲的密碼。
由於您已經在使用flask
,因此您可以使用它的一個依賴關係werkzeug
,這使得此任務變得非常簡單。
欲瞭解更多詳細看here
from werkzeug.security import generate_password_hash, check_password_hash
# when creating a user whose password is 'password'
password = the_password_the_user_specified()
hashed = generate_password_hash(password)
# take a look at the result: it's a salted and hashed password
# now save the user with the hashed password in your database
# when a user wants to log in
# select the password hash for the username the user entered in your form
password = the_password_the_user_entered()
hashed = database_get_password_for_user()
# now compare the passwords
matches = check_password_hash(hashed, password)
if matches:
# login
else:
# wrong password
所以對於「加密」使用generate_password_hash(entered)
和保存,而不是明文密碼和解密用戶check_password_hash(hashed, entered)
這一點。當用戶想要登錄並比較兩個哈希時,請不要犯這個錯誤並使用generate_password_hash
。那不起作用因爲鹽不同。
我對此使用bcrypt https://pypi.python.org/pypi/bcrypt/2.0.0。這是創建哈希的另一種選擇。
如果我有我的User類兩種方法:
import requests, bcrypt, pymongo
....
class User:
def __init__(self, db, config):
self.users = db['users']
self.config = config
def pwd_set(self, id, pwd):
h = bcrypt.hashpw(pwd.encode('utf-8'), self.config['SALT'])
self.users.update_one({'_id': id},{"$set":{"password":h, "modified":datetime.utcnow()}})
def pwd_match(self, client_pwd, server_pwd):
h = bcrypt.hashpw(client_pwd.encode('utf-8'), self.config['SALT'])
return h == server_pwd
你必須在這種情況下使用它在散列這可能不是最好的選擇鹽預先定義。 每當必須將純文本轉換爲散列值時,我使用pwd_set,並且每當必須檢查密碼是否匹配時,我都使用pwd_match方法來驗證文本是否與數據庫密碼散列中的加密相同。