Login in ASP.NET MVC - FormsAuthentication

In this article, we will perform a login operation using ASP.NET MVC 5. After the login operation, we will check the users who logs in to our website.


First of all, we create a class named LoginModel in the Models folder.


using System.ComponentModel.DataAnnotations;

namespace Login.Models
{

    public class LoginModel
    {
        [Required(ErrorMessage = "Please Enter Username")]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please Enter Password")]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

As you can see above, we have added validation contols to the LoginModel classes. To use these controls, we need to reference the System.ComponentModel.DataAnnotations library.


We create a new Controller named LoginController in the Controllers folder. Then create an Action named Login as shown below.


using System;
using System.Web.Mvc;
using System.Web.Security;

namespace Login.Controllers
{
    public class LoginController : Controller
    {
        [AllowAnonymous]
        public ActionResult Login()
        {
            if(String.IsNullOrEmpty(HttpContext.User.Identity.Name))
            {
                FormsAuthentication.SignOut();
                return View();
            }
            return Redirect("/Home/Index");
        }
    }
}

We have defined an attribute named AllowAnonymous on the Login action we created. This attribute provides an entry for all users. If the user is not in the system, FormsAuthentication.SignOut works and the Login page is viewed again.


If the user is already in the system, the user goes to the /Home/Index page.


We write another action with the same name using the HttpPost attribute.


[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model)
{
    if(ModelState.IsValid)
    {
        if(model.UserName == "Leonardo" && model.Password == "12345")
        {
            FormsAuthentication.SetAuthCookie(model.UserName, true);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            ModelState.AddModelError("", "Username or Password is incorrect!");
        }
    }
    return View(model);
}

To make sure the user is signed out when the browser is closed, use FormsAuthentication.SetAuthCookie to set the createPersistentCookie parameter to false.


We add the following code snippet between the system.web tags in the Web.config file. We set the FormsAuthentication to 1440 minutes. But when the server gets no request during 20 minutes, the authentication will expire. This is controlled by the Application Pool setting (Idle Time-out(minutes)) :


FormsAuthentication_ASPNET_MVC_1.png

<authentication mode="Forms">
	<forms loginUrl="~/Login/Login" timeout="1440" protection="All" defaultUrl="~/Home/Index"/>
</authentication>

The HTML code on the front side is as follows. (Login.cshtml)

@{
    ViewBag.Title = "Login";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@model Login.Models.LoginModel
<h2>Login</h2>
@using (Html.BeginForm("Login", "Login", FormMethod.Post))
{

    <div class="form-group">

        @Html.LabelFor(m => m.UserName)
        @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", placeholder = "Enter Username" })

    </div>
    <div class="form-group">

        @Html.LabelFor(m => m.Password)
        @Html.PasswordFor(m => m.Password, new { @class = "form-control", placeholder = "Enter Password" })

    </div>

    @*
    <div class="form-group">
	    @Html.LabelFor(m=> m.RememberMe)
	    @if(@ViewBag.remember == true)
	    {
		    @Html.CheckBoxFor(m => m.RememberMe, new { @checked="checked"})
	    }
	    else
	    {
		    @Html.CheckBoxFor(m => m.RememberMe)
	    }
    </div>
    *@

    <button type="submit" class="btn btn-primary">Log in</button>

}


The login operation is carried out in this way. The action we wrote to exit the login operation is as follows.

public ActionResult LogOff()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Login", "Login");
}

If the user is logged in, how can we confirm the login. The way to do this is pretty simple. First of all, we create a folder named ActionFilters in the root directory and then we add a class named SimpleActionFilter in the ActionFilters folder. Our class is as follows.


using System.Web;
using System.Web.Mvc;

namespace Login.ActionFilters
{
    public class SimpleActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (!HttpContext.Current.Response.IsRequestBeingRedirected)
                    filterContext.HttpContext.Response.Redirect("/Login/Login");
            }
        }
    }
}

This attribute will be used on any action or on any controller:


[SimpleActionFilter]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";

    return View();
}


using Login.ActionFilters;
using System.Web.Mvc;

namespace Login.Controllers
{
    [SimpleActionFilter]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

TEST : Username : Leonardo, Password : 12345


FormsAuthentication_ASPNET_MVC_2.png

FormsAuthentication_ASPNET_MVC_3.png

Download the source code.


tag : login asp.net mvc 5,FormsAuthentication ASP.NET MVC,FormsAuthentication asp.net mvc 5