因此,我目前正在建立一個小型資料庫用于測驗目的,并且我正在嘗試遵循一些通用安全準則,例如嘗試通過使用引數化查詢來防止 SQL 攻擊。當使用 EF Core 注冊用戶時,我通常會做一些類似的事情。
public IActionResult Register(UserModel userModel)
{
using (var ctx = new APIDbContext())
{
if (!ctx.Users.Any(x => x.Username.ToLower() == userModel.Username.ToLower()))
{
ctx.Users.Add(new UserModel
{
Username = userModel.Username,
Password = userModel.Password,
});
return Ok();
}
}
return NotFound("Username already taken.");
}
除了以純文本形式存盤密碼之外,這里還有什么特別糟糕的事情嗎?你能 SQL 注入這樣的東西嗎?有什么我應該想到的嗎?
uj5u.com熱心網友回復:
[HttpPost] // Use the right http verb.
// You dont want to submit credentials in the url, but the body.
// Put validations on the Model properties.
1. You should have your own password policy.
2. Whitelist the username characters to prevent any malicious
characters that can be compile somehow into scripts
3. Have an limit of length on every request input that will go
to the database.
// Performance Tip: Make your action async.
// async Task<IActionResult> and await on user creation function
public IActionResult Register(UserModel userModel)
{
// Add captcha to guard the application from malicious automation tools.
// It would be better to take the users email,
// for example in order to reset the password.
// If the username is his password, then ignore this point.
// Optional: Add a central or localized logging capability for security reasons.
using (var ctx = new APIDbContext())
{
if (!ctx.Users.Any(x => x.Username.ToLower() == userModel.Username.ToLower()))
{
ctx.Users.Add(new UserModel
{
Username = userModel.Username,
Password = userModel.Password, // This needs to be hashed
});
// await ctx.SaveChangesAsync()
return Ok();
}
}
return NotFound("Username already taken.");
}
我在代碼的注釋中為您提供了指導。
uj5u.com熱心網友回復:
只要你使用linq查詢,它們就不容易受到傳統的 SQL 注入攻擊。這樣Entity Framework通過SQL引數傳遞資料。此外,當密碼以純文本形式存盤時,任何知道資料庫密碼的人都可以獲取它們并登錄到任何用戶組態檔。所以他們需要在資料庫中進行散列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/449536.html
