Implementing a login attempt blocking feature in your ASP.NET web application can be a useful way to prevent brute-force attacks and unauthorized access attempts. In this article, we'll show you how to implement such a feature using C# and SQL Server.
To get started, we'll need to create a SQL Server database to store our login attempt data. Here's an example of a simple database schema that we can use:
CREATE TABLE LoginAttempts ( UserId int NOT NULL, AttemptCount int NOT NULL, LastAttemptTime datetime NOT NULL, CONSTRAINT PK_LoginAttempts PRIMARY KEY (UserId) );
This table will store the username of each login attempt and the time that the attempt was made. We'll use this information to determine whether a user should be blocked from further login attempts.
Here's an example of the complete C# code for implementing the login attempt blocking and unblocking mechanism using ASP.NET and a SQL Server database:
using System;using System.Configuration;using System.Data.SqlClient;public partial class Login : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (IsPostBack) {int userId = // get the user's ID from the input formstring connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;SqlConnection connection = new SqlConnection(connectionString);string query = "SELECT AttemptCount, LastAttemptTime, BlockedTime FROM LoginAttempts WHERE UserId = @UserId";SqlCommand command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@UserId", userId);connection.Open();SqlDataReader reader = command.ExecuteReader();int attemptCount = 0;DateTime lastAttemptTime = DateTime.MinValue;DateTime? blockedTime = null;if (reader.Read()) {attemptCount = (int)reader["AttemptCount"];lastAttemptTime = (DateTime)reader["LastAttemptTime"];if (!reader.IsDBNull(reader.GetOrdinal("BlockedTime"))) {blockedTime = (DateTime)reader["BlockedTime"];}}reader.Close();bool isBlocked = attemptCount >= 5 && (blockedTime == null || DateTime.Now - blockedTime.Value >= TimeSpan.FromMinutes(5));if (isBlocked) {query = "UPDATE LoginAttempts SET BlockedTime = @BlockedTime WHERE UserId = @UserId";command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@UserId", userId);command.Parameters.AddWithValue("@BlockedTime", DateTime.Now);command.ExecuteNonQuery();Response.Redirect("~/Blocked.aspx");}else {bool isValid = // validate the user's credentials (e.g. using Forms Authentication or Identity)if (isValid) {query = "UPDATE LoginAttempts SET AttemptCount = 0, LastAttemptTime = @LastAttemptTime, BlockedTime = NULL WHERE UserId = @UserId";command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@UserId", userId);command.Parameters.AddWithValue("@LastAttemptTime", DateTime.Now);command.ExecuteNonQuery();Response.Redirect("~/Success.aspx");}else {attemptCount++;query = "UPDATE LoginAttempts SET AttemptCount = @AttemptCount, LastAttemptTime = @LastAttemptTime WHERE UserId = @UserId";command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@UserId", userId);command.Parameters.AddWithValue("@AttemptCount", attemptCount);command.Parameters.AddWithValue("@LastAttemptTime", DateTime.Now);command.ExecuteNonQuery();isBlocked = attemptCount >= 5;if (isBlocked) {query = "UPDATE LoginAttempts SET BlockedTime = @BlockedTime WHERE UserId = @UserId";command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@UserId", userId);command.Parameters.AddWithValue("@BlockedTime", DateTime.Now);command.ExecuteNonQuery();Response.Redirect("~/Blocked.aspx");}else {Response.Redirect("~/Failure.aspx");}}}connection.Close();}}protected void UnblockAccounts(){string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;SqlConnection connection = new SqlConnection(connectionString);string query = "UPDATE LoginAttempts SET BlockedTime = NULL WHERE BlockedTime IS NOT NULL AND @Now - BlockedTime >= @BlockDuration";SqlCommand command = new SqlCommand(query, connection);command.Parameters.AddWithValue("@Now", DateTime.Now);command.Parameters.AddWithValue("@BlockDuration", TimeSpan.FromMinutes(5));connection.Open();command.ExecuteNonQuery();connection.Close();}}
<configuration><connectionStrings><add name="DefaultConnection" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings></configuration>