You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask应用中于POST请求发送前加密密码?

如何在发送POST请求前对密码加密

第一步:解决前端BCrypt未定义的错误

你遇到的bcrypt未定义是因为没有正确引入BCrypt的JavaScript库。可以使用bcryptjs(BCrypt的JS实现)的CDN来引入:

<script src="https://cdn.jsdelivr.net/npm/bcryptjs@2.4.3/dist/bcrypt.min.js"></script>

第二步:修正前端加密代码

推荐使用异步哈希方法(避免阻塞页面主线程),修改后的前端代码如下:

document.querySelector("form").addEventListener("submit", async function (event) {
  event.preventDefault(); // 阻止默认提交行为
  const passwordInput = document.querySelector("#password");
  const plainPassword = passwordInput.value;
  
  // 异步生成密码哈希,盐值因子设为10
  const hashedPassword = await bcrypt.hash(plainPassword, 10);
  
  // 将输入框的值替换为哈希后的密码
  passwordInput.value = hashedPassword;
  
  // 提交表单
  this.submit();
});

如果坚持用同步方法,可将await bcrypt.hash替换为bcrypt.hashSync(plainPassword, 10),但同步操作在哈希过程中可能短暂阻塞页面。

第三步:调整后端验证逻辑

现在前端传过来的是哈希后的密码字符串,你需要同步调整后端验证逻辑,否则直接用原逻辑比对会失败:

@accounts_bp.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated:
        flash("You are already logged in.", "info")
        return redirect(url_for("core.index"))
    
    form = LoginForm(request.form)
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        # 注意:此时request.form["password"]是前端哈希后的字符串,需用它匹配数据库中的哈希
        # 注册流程也要同步调整:前端先哈希密码,后端将该哈希值用BCrypt加密后存入数据库
        if user and bcrypt.check_password_hash(user.password, request.form["password"]):
            login_user(user)
            return redirect(url_for("core.index"))
        else:
            flash("Invalid email and/or password.", "danger")
            return render_template("accounts/login.html", form=form)
    return render_template("accounts/login.html", form=form)

重要提示

前端加密只是补充手段,启用HTTPS才是防止密码在传输过程中被截获的根本方法。HTTPS会对整个HTTP请求加密,即使明文传输密码,也不会被第三方截获破解。

内容的提问来源于stack exchange,提问作者mdegraaff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 04:35:57