繁体   English   中英

如何使用 EF Core 安全地注册用户

[英]How do I safely register a user using EF Core

因此,我目前正在建立一个用于测试目的的小型数据库,并且我正在尝试遵循一些一般安全准则,例如尝试通过使用参数化查询来防止 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 可以注入这样的东西吗?有什么我应该想到的吗?

        [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."); 
            }

我在您的代码的评论中为您提供了指导方针。

只要您使用linq查询,它们就不会受到传统的 SQL 注入攻击。这样Entity Framework通过SQL参数传递数据。 此外,当密码以纯文本形式存储时,任何知道数据库密码的人都可以获取它们并登录到任何用户配置文件。 所以他们需要在数据库中进行哈希处理。

暂无
暂无

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

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