如何使用 Python Flask-Security 使用 bcrypt 加密密码?
How to encrypt password using Python Flask-Security using bcrypt?
我正在尝试使用 Flask-Security 文档中的标准基本示例并使其正常工作,但密码以明文形式存储。
我知道这行:
user_datastore.create_user(email='matt@nobien.net', password='password')
我可以更改为:
user_datastore.create_user(email='matt@nobien.net', password=bcrypt.hashpw('password', bcrypt.gensalt()))
但我认为 Flask-Security 负责(双重?)加盐加密,如果我添加 app.config['SECURITY_REGISTERABLE'] = True 并转到 /register 数据库,这一次是正确加密。
我知道我遗漏了一些简单的东西,但不太明白在哪里..
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
import bcrypt
# Create app
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db'
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = b'b$wqKlYjmOfXPghx3FuC3Pu.'
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
try:
db.create_all()
user_datastore.create_user(email='matt@nobien.net', password='password')
db.session.commit()
except:
db.session.rollback()
print("User created already...")
# Views
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
您可以使用 python 的原生装饰器来存储密码的散列版本,而不是存储密码,并且出于安全目的使密码不可读,如下所示:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password_hash = db.Column(db.String(128))
@property
def password(self):
raise AttributeError('password not readable')
@password.setter
def password(self, password):
self.password_hash = bcrypt.hashpw('password', bcrypt.gensalt()))
# or whatever other hashing function you like.
您应该添加与您实施的 bcrypt 技术内联的验证密码功能:
def verify_password(self, password)
return some_check_hash_func(self.password_hash, password)
然后你可以用通常的方式创建一个用户:
User(email='a@example.com', password='abc')
并且您的数据库应该填充散列 password_hash
而不是 password
属性。
你说得对,create_user()
没有对密码进行哈希处理。这是一个lower-level method。如果您能够改用 registerable.register_user()
,那么它将为您散列密码。但是如果你想直接使用create_user()
,那么在调用之前加密密码即可:
from flask import request
from flask_security.utils import encrypt_password
@bp.route('/register/', methods=['GET', 'POST'])
@anonymous_user_required
def register():
form = ExtendedRegistrationForm(request.form)
if form.validate_on_submit():
form_data = form.to_dict()
form_data['password'] = encrypt_password(form_data['password'])
user = security.datastore.create_user(**form_data)
security.datastore.commit()
# etc.
我不建议覆盖用户对象上的密码散列,因为 Flask-Security 使用 SECURITY_PASSWORD_HASH
设置来存储密码散列算法。 (它 defaults to bcrypt
, so you don't need to set this explicitly if you don't want to.) Flask-Security uses HMAC to salt the password, in addition to the SECURITY_PASSWORD_SALT
which you provide, so just hashing the password using e.g. passlib with bcrypt won't result in a hash that Flask-Security will correctly match。您可以通过将 Flask-Security 退出循环并自己完成所有密码创建和比较任务来 side-step 这个……但这有什么意义呢?您正在使用安全库,让它为你做安全。他们已经修复了你绑定到 运行 的错误。
我正在尝试使用 Flask-Security 文档中的标准基本示例并使其正常工作,但密码以明文形式存储。
我知道这行:
user_datastore.create_user(email='matt@nobien.net', password='password')
我可以更改为:
user_datastore.create_user(email='matt@nobien.net', password=bcrypt.hashpw('password', bcrypt.gensalt()))
但我认为 Flask-Security 负责(双重?)加盐加密,如果我添加 app.config['SECURITY_REGISTERABLE'] = True 并转到 /register 数据库,这一次是正确加密。
我知道我遗漏了一些简单的东西,但不太明白在哪里..
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
import bcrypt
# Create app
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db'
app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
app.config['SECURITY_PASSWORD_SALT'] = b'b$wqKlYjmOfXPghx3FuC3Pu.'
# Create database connection object
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
description = db.Column(db.String(255))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean())
confirmed_at = db.Column(db.DateTime())
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
@app.before_first_request
def create_user():
try:
db.create_all()
user_datastore.create_user(email='matt@nobien.net', password='password')
db.session.commit()
except:
db.session.rollback()
print("User created already...")
# Views
@app.route('/')
@login_required
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run()
您可以使用 python 的原生装饰器来存储密码的散列版本,而不是存储密码,并且出于安全目的使密码不可读,如下所示:
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password_hash = db.Column(db.String(128))
@property
def password(self):
raise AttributeError('password not readable')
@password.setter
def password(self, password):
self.password_hash = bcrypt.hashpw('password', bcrypt.gensalt()))
# or whatever other hashing function you like.
您应该添加与您实施的 bcrypt 技术内联的验证密码功能:
def verify_password(self, password)
return some_check_hash_func(self.password_hash, password)
然后你可以用通常的方式创建一个用户:
User(email='a@example.com', password='abc')
并且您的数据库应该填充散列 password_hash
而不是 password
属性。
你说得对,create_user()
没有对密码进行哈希处理。这是一个lower-level method。如果您能够改用 registerable.register_user()
,那么它将为您散列密码。但是如果你想直接使用create_user()
,那么在调用之前加密密码即可:
from flask import request
from flask_security.utils import encrypt_password
@bp.route('/register/', methods=['GET', 'POST'])
@anonymous_user_required
def register():
form = ExtendedRegistrationForm(request.form)
if form.validate_on_submit():
form_data = form.to_dict()
form_data['password'] = encrypt_password(form_data['password'])
user = security.datastore.create_user(**form_data)
security.datastore.commit()
# etc.
我不建议覆盖用户对象上的密码散列,因为 Flask-Security 使用 SECURITY_PASSWORD_HASH
设置来存储密码散列算法。 (它 defaults to bcrypt
, so you don't need to set this explicitly if you don't want to.) Flask-Security uses HMAC to salt the password, in addition to the SECURITY_PASSWORD_SALT
which you provide, so just hashing the password using e.g. passlib with bcrypt won't result in a hash that Flask-Security will correctly match。您可以通过将 Flask-Security 退出循环并自己完成所有密码创建和比较任务来 side-step 这个……但这有什么意义呢?您正在使用安全库,让它为你做安全。他们已经修复了你绑定到 运行 的错误。