Building a Secure Login System in .NET MVC: A Step-by-Step Guide

One of the most important features of any web application is the login system. In this post, I will walk you through the steps to create a login system in .NET MVC, complete with code examples.

Setting Up the Project

The first step in creating a login system is to set up a new .NET MVC project. Follow these steps to set up a new project:

  1. Open Visual Studio and select File > New > Project.
  2. In the New Project dialog box, select ASP.NET Web Application and give your project a name.
  3. In the next window, select the MVC template and click on Create.

Now that your project is created, you can start creating the login system.

Creating a User Model

To create a user model, follow these steps:

  1. Right-click on the Models folder in the Solution Explorer and select Add > Class.
  2. Name the class UserModel and click on Add.
  3. In the UserModel class, add the following properties:
public class UserModel
{
    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

In the above code, we have defined three properties, namely Id, Username, and Password. These properties represent the user's unique identifier, username, and password.

Creating a Database

Next, we need to create a database to store user information. Follow these steps to create a database:

  1. Right-click on the project name in the Solution Explorer and select Add > New Item.
  2. Select the SQL Server Database template and give your database a name.
  3. Click on Add to create the database.

Once the database is created, we need to create a table to store user information. Follow these steps to create a table:

  1. Open the Server Explorer and connect to your database.

  2. Right-click on the Tables folder and select Add New Table.

  3. In the new table designer window, add the following columns:

    • Id (int, primary key)
    • Username (nvarchar)
    • Password (nvarchar)
  4. Save the table by clicking on the Save button.

Creating a Data Access Layer

Now that we have created the database and user model, we need to create a data access layer to interact with the database. Follow these steps to create a data access layer:

  1. Right-click on the project name in the Solution Explorer and select Add > New Folder.
  2. Name the folder DataAccessLayer.
  3. Right-click on the DataAccessLayer folder and select Add > Class.
  4. Name the class UserDataAccessLayer and click on Add.
  5. In the UserDataAccessLayer class, add the following code:
public class UserDataAccessLayer
{
    private string connectionString = ConfigurationManager.ConnectionStrings["UserDatabase"].ConnectionString;

    public bool AddUser(UserModel user)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "INSERT INTO Users (Username, Password) VALUES (@Username, @Password)";

            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@Username", user.Username);
            command.Parameters.AddWithValue("@Password", user.Password);

            connection.Open();
            int result = command.ExecuteNonQuery();
            connection.Close();

            return result > 0;
        }
    }

    public UserModel GetUser(string username, string password)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            string query = "SELECT * FROM Users WHERE Username = @Username AND Password = @Password";

            SqlCommand command = new SqlCommand(query, connection);
            command.Parameters.AddWithValue("@Username", username);
            command.Parameters.AddWithValue("@Password", password);

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            UserModel user = null;
            if (reader.Read())
            {
                user = new UserModel();
                user.Id = (int)reader["Id"];
                user.Username = reader["Username"].ToString();
                user.Password = reader["Password"].ToString();
            }

            reader.Close();
            connection.Close();

            return user;
        }
    }
}

In the above code, we have created two methods, namely AddUser and GetUser. The AddUser method is responsible for inserting a new user into the database, and the GetUser method is responsible for retrieving a user from the database based on their username and password.

Creating a Controller

Now that we have created the user model, database, and data access layer, we can create a controller to handle user requests. Follow these steps to create a controller:

  1. Right-click on the Controllers folder in the Solution Explorer and select Add > Controller.
  2. Name the controller LoginController and click on Add.
  3. In the LoginController, add the following code:
public class LoginController : Controller
{
    private UserDataAccessLayer userDataAccessLayer = new UserDataAccessLayer();

    // GET: Login
    public ActionResult Index()
    {
        return View();
    }

    // POST: Login
    [HttpPost]
    public ActionResult Index(UserModel user)
    {
        UserModel foundUser = userDataAccessLayer.GetUser(user.Username, user.Password);
        if (foundUser != null)
        {
            FormsAuthentication.SetAuthCookie(foundUser.Username, false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Invalid username or password.");
            return View();
        }
    }

    // GET: Logout
    public ActionResult Logout()
    {
        FormsAuthentication.SignOut();
        return RedirectToAction("Index", "Home");
    }
}

In the above code, we have created three methods, namely Index, Logout, and the HttpPost Index. The Index method is responsible for displaying the login form to the user, the HttpPost Index method is responsible for validating the user's login credentials and setting the authentication cookie, and the Logout method is responsible for signing the user out.

Creating the Views

Now that we have created the controller, we need to create the views. Follow these steps to create the views:

  1. Right-click on the Views folder in the Solution Explorer and select Add > Folder.
  2. Name the folder Login.
  3. Right-click on the Login folder and select Add > View.
  4. Name the view Index and click on Add.
  5. In the Index view, add the following code:
@model UserModel

@{
    ViewBag.Title = "Login";
}

Login

@using (Html.BeginForm()) { @Html.AntiForgeryToken()
@Html.LabelFor(model => model.Username) @Html.TextBoxFor(model => model.Username, new { @class = "form-control" })
@Html.LabelFor(model => model.Password) @Html.PasswordFor(model => model.Password, new { @class = "form-control" })
}

In the above code, we have created a login form using HTML helpers. The login form will accept the user's username and password, which will then be passed to the controller for validation.

 
Asp.Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
1 + 2 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice