Authentication in ASP.NET MVC With Example

Authentication in ASP.NET MVC allows you to identify and verify users before granting access to protected parts of the application. Here's a high-level overview of how authentication works in ASP.NET MVC (non-Core) and how to implement it.





✅ Types of Authentication in ASP.NET MVC

  1. Forms Authentication (Traditional)
  2. Windows Authentication
  3. OAuth / External Login (Google, Facebook, etc.)
  4. Token-Based Authentication (JWT, often with Web API)

For most web apps, Forms Authentication is commonly used.


🔐 1. Forms Authentication (with Login Page)

✅ Steps:

1. Enable Forms Authentication in Web.config:


<configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="30" /> </authentication> <authorization> <deny users="?" /> <!-- Deny anonymous users --> </authorization> </system.web> </configuration>

2. Create Login View + Controller Logic:

Model:

public class LoginViewModel
{ public string Username { get; set; } public string Password { get; set; } }

Controller:

public class AccountController : Controller
{ public ActionResult Login() => View(); [HttpPost] public ActionResult Login(LoginViewModel model) { if (IsValidUser(model.Username, model.Password)) { FormsAuthentication.SetAuthCookie(model.Username, false); return RedirectToAction("Index", "Home"); } ModelState.AddModelError("", "Invalid login attempt."); return View(model); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); } private bool IsValidUser(string username, string password) { // Replace with DB check or identity logic return username == "admin" && password == "1234"; } }

View (Login.cshtml):

@model YourApp.Models.LoginViewModel
@using (Html.BeginForm()) { <label>Username</label> @Html.TextBoxFor(m => m.Username) <label>Password</label> @Html.PasswordFor(m => m.Password) <button type="submit">Login</button> }

🔐 2. Protecting Actions with [Authorize]

Use this to restrict access:

[Authorize]
public ActionResult SecurePage() { return View(); }

To allow anonymous access:


[AllowAnonymous] public ActionResult Login() => View();

🔄 Redirect on Session Expiry

ASP.NET will automatically redirect to the login page if the user is not authenticated, based on the loginUrl in Web.config.


🔑 Alternative: ASP.NET Identity (for more advanced use)

If you're using ASP.NET Identity (like with Visual Studio templates), authentication becomes more powerful with roles, claims, password recovery, etc.



✅ Goal: Authentication in ASP.NET MVC using Forms Authentication + SQL Server

🧱 Structure Overview

  • ✅ SQL Server with Users table
  • ✅ ASP.NET MVC Login screen
  • ✅ Authenticate and store the cookie using FormsAuthentication
  • ✅ Restrict access using [Authorize]


🗃️ 1. SQL Server Table (Users)



CREATE TABLE Users ( Id INT PRIMARY KEY IDENTITY, Username NVARCHAR(100) NOT NULL, Password NVARCHAR(100) NOT NULL );

Add a test user:


INSERT INTO Users (Username, Password) VALUES ('admin', '1234'); -- store hashed passwords in production!

🔌 2. Set Up Your MVC Project

  1. Create an ASP.NET MVC Project (Visual Studio → New Project → ASP.NET MVC).
  2. Add an ADO.NET Entity Data Model to connect to your Users table.


🧑‍💻 3. Create Login Model


public class LoginViewModel { [Required] public string Username { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } }

🎮 4. Create Account Controller


public class AccountController : Controller { private YourDbContext db = new YourDbContext(); // Replace with your EF context public ActionResult Login() => View(); [HttpPost] public ActionResult Login(LoginViewModel model) { if (ModelState.IsValid) { var user = db.Users.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password); if (user != null) { FormsAuthentication.SetAuthCookie(user.Username, false); return RedirectToAction("Index", "Home"); } ModelState.AddModelError("", "Invalid username or password."); } return View(model); } public ActionResult Logout() { FormsAuthentication.SignOut(); return RedirectToAction("Login", "Account"); } }

🧾 5. View (Login.cshtml)


@model YourNamespace.Models.LoginViewModel @using (Html.BeginForm()) { @Html.LabelFor(m => m.Username) @Html.TextBoxFor(m => m.Username) @Html.ValidationMessageFor(m => m.Username) @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password) @Html.ValidationMessageFor(m => m.Password) <button type="submit">Login</button> }

🔐 6. Protect Pages Using [Authorize]


[Authorize] public class HomeController : Controller { public ActionResult Index() { return View(); } }

⚙️ 7. Web.config Configuration


<system.web> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="30" /> </authentication> <authorization> <deny users="?" /> </authorization> </system.web>

✅ 8. Done! Now:

  • Visit any secure page → redirected to Login
  • Enter correct credentials from DB → redirected to Home
  • Click Logout → session removed


🔒 Security Note

  • In real applications, store passwords as hashes (e.g., SHA256 or bcrypt).
  • You can use ASP.NET Identity for more secure systems with role management, password hashing, and email verification.

⚠️ Without Authentication

  • Anyone can change your data
  • No audit trail of who did what
  • Can’t protect sensitive features
  • Security threats (unauthorized access, data leaks)

Post a Comment

Post a Comment (0)

Previous Post Next Post