假設我有一個包含以下資料的 MongoDB 檔案:
{
"username": "test123",
"password": "$2b$10$M2Y3ELsgfvA4KHxdCJkezeHZ1kKgtOA2Jiq4kuwqcRJSovGBu9nLm"
}
密碼使用bcrypt. 使用 MongoDB 的官方 Node 驅動程式,我可以找到用戶名:
collection.findOne({ username: req.body.username });
但是如何找到用戶名,然后查看password同一個檔案的值(與用戶名相關的密碼),最后回傳密碼呢?
附注。我知道標題很混亂,如果你能想到更好的表達方式,請在下面評論。
uj5u.com熱心網友回復:
將加密密碼發送到資料庫是不好的做法。它有一些安全問題。我猜您想通過用戶名獲取用戶,通過比較其密碼(密碼哈希)來確定它是否是您獲取的正確用戶,然后對該用戶執行某些操作 - 例如,回傳密碼左右,正如您所提到的(我不明白你為什么要向任何人公開密碼)。對于加密,我使用的是bcryptjs package,但它非常相似。它的函式compare()將原始密碼作為第一個引數,并將資料庫中的散列密碼作為第二個引數。它對原始密碼進行散列并將其與給定的散列進行比較。如果哈希匹配,則密碼有效。對于代碼,您將有以下內容:
const bcrypt = require('bcryptjs');
// ...
const user = await collection.findOne({ username: req.body.username });
if (!user) throw new Error('User doesn\'t exist');
// first argument "password" is a raw password to compare with the one in the document
const passwordValid = await bcrypt.compare(password, user.password);
if (!passwordValid) throw new Error('Invalid password');
// do whatever you want to do with validated user
// if you want password to return, raw "password" is the one that's in the database also (hash)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/314285.html
