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. public ActionResult Index()
  7. {
  8. return View();
  9. }
  10. //[ValidateAntiForgeryToken]
  11. [HttpPost]
  12. [AllowAnonymous]
  13. public ActionResult Login()
  14. {
  15. string u = Request["use"];
  16. string p = Request["pass"];
  17. string name = AuthUser(u,p);
  18. if (!(String.IsNullOrEmpty(name)))
  19. {
  20. Session["UserName"] = name;
  21. return RedirectToAction("home", "Default");
  22. }
  23. return RedirectToAction("Index","Default");
  24. }
  25. public ActionResult home()
  26. {
  27. return View();
  28. }
  29. public string AuthUser(string username, string password)
  30. {
  31. if (password.Equals("123") && username.Equals("user"))
  32. return "User";
  33. else
  34. return null;
  35. }
  36. }
Index.cshtml code is,
  1. @{
  2. Layout = null;
  3. }
  4. <!DOCTYPE html>
  5. <html>
  6. <head>
  7. <meta name="viewport" content="width=device-width" />
  8. <title>Index</title>
  9. </head>
  10. <body>
  11. <div>
  12. @using(Html.BeginForm("Login","Default",FormMethod.Post))
  13. {
  14. <input type="text" name="use" placeholder="Enter The Name" /><br/>
  15. <input type="password" name="pass" placeholder="Enter The Password" /><br/>
  16. <input type="submit" value="submit" />
  17. }
  18. </div>
  19. </body>
  20. </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. // Check for authorization
  12. if (HttpContext.Current.Session["UserName"] == null)
  13. {
  14. filterContext.Result = new RedirectResult("~/Default/Index");
  15. }
  16. }
  17. }
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.