Applying Authorization Using Session In ASP.NET MVC

Add new empty MVC project. Then add a new controller in it.

Controller Code is as follows,
  1. public class DefaultController : Controller  
  2.    {  
  3.        // GET: Default  
  4.        [HttpGet]  
  5.        [AllowAnonymous]  
  6.          
  7.        public ActionResult Index()
  8.        {  
  9.            return View();  
  10.        }  
  11.        //[ValidateAntiForgeryToken]  
  12.   
  13.        [HttpPost]  
  14.        [AllowAnonymous]  
  15.        public ActionResult Login()  
  16.        {  
  17.            string u = Request["use"];  
  18.            string p = Request["pass"];  
  19.            string name = AuthUser(u,p);  
  20.            if (!(String.IsNullOrEmpty(name)))  
  21.            {  
  22.                Session["UserName"] = name;  
  23.                return RedirectToAction("home""Default");  
  24.            }  
  25.            return RedirectToAction("Index","Default");  
  26.        }  
  27.        public ActionResult home()  
  28.        {  
  29.            return View();  
  30.        }  
  31.        public string AuthUser(string username, string password)  
  32.        {  
  33.            if (password.Equals("123") && username.Equals("user"))  
  34.                return "User";  
  35.            else  
  36.                return null;  
  37.        }  
  38.   
  39.    } 
 Index.cshtml code is,
  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Index</title>  
  11. </head>  
  12. <body>  
  13.     <div>  
  14.         @using(Html.BeginForm("Login","Default",FormMethod.Post))  
  15.         {  
  16.             <input type="text" name="use" placeholder="Enter The Name" /><br/>  
  17.             <input type="password" name="pass" placeholder="Enter The Password" /><br/>  
  18.             <input type="submit" value="submit" />  
  19.         }  
  20.     </div>  
  21. </body>  
  22. </html>   
After adding the code to the controller and making views add a new class name, AuthorizationFilter, in App_Start Folder.

The Class Code is, 
  1. public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter  
  2.    {  
  3.        public override void OnAuthorization(AuthorizationContext filterContext)  
  4.        {  
  5.            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)  
  6.                || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))  
  7.            {  
  8.                // Don't check for authorization as AllowAnonymous filter is applied to the action or controller  
  9.                return;  
  10.            }  
  11.   
  12.            // Check for authorization  
  13.            if (HttpContext.Current.Session["UserName"] == null)  
  14.            { 
  15.                filterContext.Result = new RedirectResult("~/Default/Index");  
  16.            }  
  17.        }  
  18.    } 
Now Open Global.asax

Add this line in protected void Application_Start()
  1. GlobalFilters.Filters.Add(new AuthorizationFilter());
In last open Web.config add this line in <system.web>
  1. <system.web>  
  2. <sessionState timeout="1"></sessionState>  
  3.   </system.web> 
  You will be redirected to Index page when session expires and then no one has to log in again.