简体   繁体   English

如何使用bcrypt使用Python Flask-Security加密密码?

[英]How to encrypt password using Python Flask-Security using bcrypt?

I'm trying to utlise the standard basic example in the docs for Flask-Security and have made it work except for the password being stored in plaintext. 我正在尝试在Flask-Security的文档中使用标准的基本示例,并使其能够正常工作,只是密码以明文形式存储。

I know this line: 我知道这一行:

user_datastore.create_user(email='matt@nobien.net', password='password')

I could change to: 我可以更改为:

user_datastore.create_user(email='matt@nobien.net', password=bcrypt.hashpw('password', bcrypt.gensalt()))

But I thought Flask-Security took care of the (double?) salted encryption and if I add the app.config['SECURITY_REGISTERABLE'] = True and go to /register the database this time IS encrypted correctly. 但是我认为Flask-Security负责(双重?)盐腌加密,如果我添加了app.config ['SECURITY_REGISTERABLE'] = True,并且这次正确地对数据库进行了/ register加密。

I know I am missing something simple but don't quite understand where.. 我知道我缺少一些简单的东西,但不太了解。

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'$2b$12$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()

Instead of storing the password you can use python's native decorators to store a hashed version of the password instead and make the password unreadable for security purposes, like this: 除了存储密码,您还可以使用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.

You should add a verify password function inline with the bcrypt technolgy you implement: 您应该在实现的bcrypt技术中内嵌验证密码功能:

    def verify_password(self, password)
        return some_check_hash_func(self.password_hash, password)

Then you can create a user with the usual: 然后,您可以使用通常的方式创建用户:

User(email='a@example.com', password='abc')

and your Database should be populated with a hashed password_hash instead of a password attribute. 并且您的数据库应使用散列的password_hash而不是password属性填充。

You're right, create_user() doesn't hash the password. 没错, create_user()不会对密码进行哈希处理。 It is a lower-level method . 这是一种较低级别的方法 If you are able to use registerable.register_user() instead, then it will hash the password for you. 如果您能够改用registerable.register_user() ,则它将为您哈希密码。 But if you would like to use create_user() directly, then just encrypt the password before calling it: 但是,如果您想直接使用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.

I wouldn't recommend overriding the password hashing on the User object, since Flask-Security uses the SECURITY_PASSWORD_HASH setting to store the password hashing algorithm. 我不建议在User对象上覆盖密码哈希,因为Flask-Security使用SECURITY_PASSWORD_HASH设置存储密码哈希算法。 (It 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 eg passlib with bcrypt won't result in a hash that Flask-Security will correctly match . 默认bcrypt ,因此,如果您不想这样做,则无需显式设置。)Flask-Security除了使用您提供的SECURITY_PASSWORD_SALT之外,还使用HMAC来对密码加盐 ,因此只需使用例如,带有bcrypt的passlib 不会导致Flask-Security正确匹配的哈希 You might be able to side-step this by cutting Flask-Security out of the loop and doing all password creation and comparison tasks yourself… but what's the point? 您也许可以通过将Flask-Security切入循环并自己完成所有密码创建和比较任务来避开此事,但这有什么意义呢? You're using a security library, let it do security for you. 您正在使用安全性库,让它为您做安全性。 They've already fixed the bugs you're bound to run into. 他们已经修复了您必然会遇到的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM