Click here to Skip to main content
15,358,707 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to restrict user for 30 minutes, after 3 invalid login attempts in code

There is a few ways to do this.

1) Add a session variable with DateTime "banned" and check it to see if it's more then 30 min ago
Pros: Extremely easy to implement. Will not affect any other users.
Cons: Extremely easy to bypass (close and reopen browser)

2) Add a cookie which expires after 30 minutes
Pros: Easy to implement. Will not affect any other users.
Cons: Easy to bypass. (just delete the cookie)

3) Create a table in your database keeping IP-address and DateTime for time "banned"
Pros: Difficult to bypass
Cons: A little bit more work to implement. Will potentially affect other users with same IP. (you can solve this by storing more info about user like user agent string, but it's not bullet proof)

4) Store UserId and when the login attempt failed in the database
Pros: Impossible to bypass
Cons: Can lock out a user which didn't try to log in. Ex if I try to log in with someone else's username. Some work to implement.

Alt 4 is the best solution here!
You need a storage location possibly SQL where you store the username and occurred time of a failed log in:

Username VARCHAR(255),

The the following SQL will give you the failed login count.

SELECT [Count] = COUNT(*) FROM dbo.FailedAttempts WHERE Username=@Username AND Occurred > DATEADD(MINUTE, -30, GETDATE())

You then need to build this into you login process so that if the user login fails you insert into the failed attempts table. If the password is valid you check the current failed attempts count and reject their attempt where it's too high.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900