Introduction:
In today's interconnected digital world, securing user data and authentication is paramount. One of the tried-and-true methods for achieving this is through forms authentication. In this blog post, we will explore how to implement forms authentication in a .NET application, ensuring robust security and a seamless user experience. Get ready to dive into the step-by-step guide and unlock the full potential of forms authentication!
Forms Authentication:
Forms authentication is a method used in web applications to manage user authentication and authorization. It involves collecting user credentials (typically a username and password) through an HTML form and verifying them against a user database or directory. Once authenticated, the user is granted access to restricted resources or functionality within the application.
The benefits of using forms authentication include:
1. User authentication: Forms authentication allows you to verify the identity of users accessing your web application. By requiring users to provide valid credentials, you can ensure that only authorized individuals can access protected resources.
2. Customizable login experience: With forms authentication, you have control over the login process. You can design and customize the login page according to your application's branding and user experience requirements. This flexibility allows you to create a seamless and consistent login experience for your users.
3. Session management: Forms authentication typically uses session cookies to manage user sessions. A session cookie is issued to the user upon successful authentication and is used to track subsequent requests. This enables the web application to identify authenticated users without requiring them to reauthenticate for every request. Session management simplifies the user experience and improves performance.
4. Authorization and access control: Once a user is authenticated, forms authentication allows you to enforce access control policies. You can define different roles or permissions and assign them to users or groups. This enables you to restrict access to specific features, pages, or resources based on the user's role, enhancing the security of your application.
Step 1: Create an ASP.NET MVC Project
1. Open Visual Studio and click on Create a new project.
2. Select ASP.NET Web Application (.NET Framework) from the list of templates and click on Next.
3. Give the name to the project and click on Create.
4. Select MVC and click on Create.
Step 2: Configure Web.config
1. We will have to configure forms authentication in our application’s web.config file. This includes specifying the login page, cookie settings, and the authentication mode.
Add the below block of code under System.web.
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880">
<credentials passwordFormat="Clear">
<user name="Admin" password="Admin@123"/>
</credentials>
</forms>
</authentication>
In this above code, the authentication mode is set to "Forms" and the loginUrl attribute specifies the URL of the login page. The timeout attribute sets the duration of the authentication ticket.
Step 3: Create a Login Controller and Views
Let’s add a new controller and add the code for the login and logout functionality.
1. Right click Controllers folder. Click on Add and then Controller.
2. Select MVC 5 Controller – Empty and click on Add.
3. Give the controller name and click on Add.
4. Add the below code on the AccountController.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace ImplementFormsAuthentication.Controllers
{
public class AccountController : Controller
{
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(string username, string password)
{
if (IsValidUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
return RedirectToAction("Index", "Home"); // Redirect to default landing page
}
else
{
ViewBag.ErrorMessage = "Invalid username or password";
return View();
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
return RedirectToAction("Login");
}
private bool IsValidUser(string username, string password)
{
return FormsAuthentication.Authenticate(username, password);
}
}
}
5. Right click on the Login action method and click on Add View.
6. Select MVC 5 View and click on Create.
7. Give the view name and click on Add.
8. Add the below code under Login view. In the below code, we are creating the form with Username and Password fields and a submit button. There is a paragraph tag below that, which is just printing the value obtained from the ViewBag.
@model dynamic
@{
ViewBag.Title = "Login";
}
<h2>Login</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div>
<label for="username">Username:</label>
@Html.TextBox("username")
</div>
<div>
<label for="password">Password:</label>
@Html.Password("password")
</div>
<input type="submit"value="Login"/>
}
<p>@ViewBag.ErrorMessage</p>
Step 4: Protect Authorized Actions
1. In the Login Action method under the AccountController, We have written the code to Redirect to the Index action method of the HomeController when the username and password in valid. To protect the Index action method from anonymous access, we need to add the Authorize attribute. With this attribute, only authorized users can access that action method. I have added the [Authorize] at the top of the HomeController.
Step 5: Change on the Layout file
1. Open the _Layout file. Add the below block of code to show the Logout button, once the user gets log in. The code below is checking whether the user is authenticated or not and showing the Logout button, if user is authenticated.
@if (User.Identity.IsAuthenticated)
{
<li>@Html.ActionLink("Logout", "Logout", "Account")</li>
}
Step 6: Demo
1. After running the project, we will get the below screen.
2. After entering the correct username and password, we will get the below screen.
The project code is available here.
Conclusion:
Forms authentication in ASP.NET MVC provides a straightforward approach to implementing user authentication in web applications. By configuring forms authentication, creating login views, validating user credentials, protecting authorized actions, and enabling logout functionality, developers can build secure and user-friendly web experiences. Incorporating forms authentication enhances the overall security and user experience of ASP.NET MVC applications.