Home > Net >  How do I safely register a user using EF Core
How do I safely register a user using EF Core

Time:03-25

So I'm currently setting up a small database for testing purposes and I'm trying to follow some general safety guidelines such as trying to prevent a SQL attack by using parameterized queries. When using EF Core to register a user I would usually do something along the lines of.

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

Besides storing the password in plain text, is there anything super bad going on here? Can you SQL inject something like this and is there anything I should think of?

CodePudding user response:

As long as you use linq queries, they are not vulnerable to traditional SQL injection attacks.In this way Entity Framework passes the data via SQL parameters. Also When passwords are stored in plain text, anyone who knows the database password, can get them and log into any user profile. So they needed to be hashed in the database.

CodePudding user response:

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

I have provided you with guidelines in the comments at your code.

  • Related