Form Based Authentication in MVC

In web based application security is a major concern. In application we have so many forms which we want to be accessed by only authentic user.

In MVC as we know that we create action which calls view accordingly. So we have to authenticate the action that whether the authorize person is going to access the action or not.

Example of Form based Authentication

In this example I am taking 3 action Home, show which showing all employee records and login which is taking username and password as input from the user.

I am taking entity framework classes to validate username and password from database.

Note: - if you are new to entity framework then Click Here.

I am using following tables for this example:-

		
create database form_authentication
use form_authentication
create table employee(id int primary key identity(1,1), name varchar(100), age int)
create table login(LoginId varchar(100) primary key, pwd varchar(100));

		
		

Employee Table

		
		form based authentication employee table
		
		Figure 1
		
		

Login Table

		
		form based authentication Login table
		
		Figure 2
		
		

Now add entity framework classes for these two tables in MVC application and add Home Controller in your application with home action.

I have created the TechAltum controller and added Home action in it. Also changed setting of controller and action in the route.config.

		
		public class TechAltumController : Controller
    {
       public ActionResult Home()
        {
            return View();
        }

    }

		

Now add view for home action

Now add login actions in which first login action will show the login window and another action is taking the input from user and authenticate whether this user is authenticated or not.

		
		[HttpGet]
       public ActionResult Login()
       {

           return View();
       
       }
        [HttpPost]
        public ActionResult Login(login data)
        {
            form_authenticationEntities fa=new form_authenticationEntities();
            int isvalid = fa.logins.Where(x => x.LoginId == data.LoginId && x.pwd == data.pwd).Count();
            if (isvalid > 0)
            {

                return  RedirectToAction("Home");
            
            }
            Response.Write("Not Valid User");

            return View();
        
        }

		

Now add view for Login action.

Now create show action in which select all data from employee table and show that data.

		
		public ActionResult Show()
        {

            form_authenticationEntities fa = new form_authenticationEntities();
            IEnumerable<employee> emp = fa.employees;
            return View(emp);
        
        }

		
		

Now add view for this action and use the scaffolding List option to show the data.

Note:-if you are new to scaffolding option then click here.

Now add login and show link on home page and back to home link on login page.

Now execute the code and you will get following window:-

		
		form based authentication home screen
		
		Figure 3
		
		

When click on Login then you will get following window

		
		form based authentication Login screen
		
		Figure 4
		
		

And when we click on Employee link it will show all the records

		
		form based authentication show all data screen
		
		Figure 5
		
		

As you can see that it’s showing all the records of all employees. Suppose I want to show this record after login. It means only authentic user can see the records.

Authorize Filter in MVC

I want only authentic user can access the records, so I have to add Authorize attribute to the action in the following manner:-

		
		[Authorize]
        public ActionResult Show()
        {

            form_authenticationEntities fa = new form_authenticationEntities();
            IEnumerable<employee> emp = fa.employees;
            return View(emp);
        
        }

		
		

Now go to web.config file and add form based authentication in System.web tag in the following manner:-

		
		form based authentication Web config setting
		
		Figure 6
		
		

Now if you execute this code whenever you will click on show link it will redirect you to the login window. Until you will not login you cannot view the employee records.

Now you have to go on login action and you have to add the authentication in the following manner:-

		
		[HttpPost]
        public ActionResult Login(login data)
        {
            //Entity framework class object
            form_authenticationEntities fa=new form_authenticationEntities();
            //checking whether user authenicated or not
            int isvalid = fa.logins.Where(x => x.LoginId == data.LoginId && x.pwd == data.pwd).Count();
            if (isvalid > 0)
            {
                //if user valid then set authentication
                
FormsAuthentication.SetAuthCookie(data.LoginId, false);
              return  RedirectToAction("Home");
            
            }
           
            //if user not valid then simply showing error message
            Response.Write("Not Valid User");

            return View();
        
        }

		

Now again execute the code and when you login you are able to see the records.

Now add logout action and sign out from the authentication in the following manner:-

!-- responsive -->
		
		public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Home");
        
        }

		
		

Now add logout link on show view.

		
		form based authentication Result
		
		Figure 7
		
		

When you click on LogOut Link now again you have to login only then you are able to access the data.

Complete TechAltum Controller Code:-

		
		using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcApplication1.Controllers
{
    public class TechAltumController : Controller
    {
       public ActionResult Home()
        {
            return View();
        }

        [HttpGet]
       public ActionResult Login()
       {

           return View();
       
       }
        [HttpPost]
        public ActionResult Login(login data)
        {
            //Entity framework class object
            form_authenticationEntities fa=new form_authenticationEntities();
            //checking whether user authenicated or not
            int isvalid = fa.logins.Where(x => x.LoginId == data.LoginId && x.pwd == data.pwd).Count();
            if (isvalid > 0)
            {
                //if user valid then set authentication
                FormsAuthentication.SetAuthCookie(data.LoginId, false);
              return  RedirectToAction("Home");
            
            }
           
            //if user not valid then simply showing error message
            Response.Write("Not Valid User");

            return View();
        
        }

       [Authorize]
        public ActionResult Show()
        {

            form_authenticationEntities fa = new form_authenticationEntities();
            IEnumerable<employee> emp = fa.employees;
            return View(emp);
        
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Home");
        
        }

    }
}
		

Email Address

For any query you can mail me at Malhotra.isha3388@gmail.com.