The simplest possible way to prevent brute-force logins

So I’m gearing up to protect one of my login forms against brute-force authentication attacks (essentially a bot guessing at a password over and over hoping for success).

I’ve read up on it and every solution I find appears to be more complex than it needs to be (involving adding multiple additional fields to the database).

After tabling it for a few days, an idea hit me. We can do this with very little code and one additional database field, as long as we setup a cron job to help us out.

Let me explain in three simple steps…

The database field

Just add one field to your users table:  login_attempts tinyint default 0

The code

During your authentication check, add login_attempts to your query’s SELECT statement.

Then, before checking the password, execute something like this (illustrated with PHP)

if ($user['login_attempts'] > 5) {
  header('Location: ../?errors=Too many failed login attempts. 
           Please try again in 5 minutes.');
  exit();
}

....

/* if login fails */
UPDATE		 users
SET		 login_attempts = login_attempts + 1
WHERE		 email = :email

The cron

A script that runs every 5 minutes and simply runs the following SQL statement:

UPDATE users
 SET login_attempts = 0

 

Perhaps I’ve under-thought this one, so let me know if anyone sees a hole in my thinking!

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs


Tagged .

Updated: 2015-02-03

Phil LaNasa follow us in feedly