Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Form authetication in MVC

    • 0
    • 4
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 406
    Comment on it

    Here I will try to explain the form authentication in MVC.

    Step-1 Let's start with a new MVC project, following steps:

    File > New > Project, a dialog box appears, select "Web" from the "Template" option, then on right side select "ASP.NET MVC 4 Web Application". On selecting MVC 4 web application, another dialog box appears where you can select the project template. For our example let's go with "Empty".


    Step-2 Let's create a model first that will correspond to the fields we will be using to authenticate the user. Go to Model folder and create a class file as "Login.cs" with following structure:

    public class Login
    {
      [Required]
      [Display(Name = "User name")]
      public string UserName { get; set; }
    
      [Required]
      [DataType(DataType.Password)]
      [Display(Name = "Password")]
      public string Password { get; set; }
    }
    

    Now build the solution.


    Step-3 Create a controller file as "AuthenticateController.cs" inside Controllers folder which is by default created as a part of project architechture. While creating contoller we will select template as "Empty MVC controller" .

    Once done with a new controller, lets create an action method as following inside AuthenticateController.cs controller file.

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
       ViewBag.ReturnUrl = returnUrl;
       return View();
    }
    

    This method will basically handling the request that is generated from the browser and will takes to the view associated with it.

    Here we have just created an action in our controller, but we still haven't created a view associated with this action. To create a view right click on this action and select "Add View" option. Now "Add View" dialog box appears, where we can specify the view engine, master page and decide whether the view will be strongly-typed view or not. We will select this option and specify the model class "Login.cs" we created in Step-1.


    Step-4 Now we will have a view generated specifying the @model property at the top as our model class "Login.cs". Now lets change the view with the following markup.

    @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
    
        <fieldset>
            <legend>Log in Form</legend>
            <ol>
                <li>
                    @Html.LabelFor(m => m.UserName)
                    @Html.TextBoxFor(m => m.UserName)
                    @Html.ValidationMessageFor(m => m.UserName)
                </li>
                <li>
                    @Html.LabelFor(m => m.Password)
                    @Html.PasswordFor(m => m.Password)
                    @Html.ValidationMessageFor(m => m.Password)
                </li>
            </ol>
            <input type="submit" value="Log in" />
        </fieldset>
    }
    

    @section Scripts {
         @Scripts.Render("~/bundles/jqueryval")
    }
    


    Step-5 As now we have a view that will be shown on hitting the action method we created in Step-3, but we don't have an action method that will handle the post request of this page which will be most probably generating after clicking "Submit" button. So let's create a Post method for the same as following:

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(Login login, string returnUrl)
        {
            //Authenticate User here
            accountAPIController = new ControllersAPI.AccountController();
            if (ModelState.IsValid && login.UserName == "test" && login.Password == "123456")
            {
                FormsAuthentication.RedirectFromLoginPage(login.UserName, true);
    
                if (!String.IsNullOrEmpty(returnUrl))
                    return View();
                else
                    return RedirectToAction("Index", "Home");
            }
    
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(login);
        }
    

    In this action we have a receiving parameter as of type Login, which is the model we selected while creating our login view. In the function definition using `ModelState.IsValid`, we are checking whether the model has all required properties filled before submitting the form. Then for our testing purpose we check whether the Username has "test" and Password is equal to "123456". If this condition is passed then we are authenticating this user by his username and creating a persistent cookie to maintain unique session.

    In case if authenticating condition fails, we are adding an error message to `ModelState` and redirecting back to the same page. In our View this line `@Html.ValidationSummary(true)` will be showing the error message.


    Step-6 To enable form authentication in our application we need to add following section in our web.config file

    <system.web>
        <authentication mode="Forms">
          <forms loginUrl="~/Account/Login" defaultUrl="~/" timeout="20" slidingExpiration="true" />
        </authentication>
     </system.web>
    

    Here loginUrl="~/Account/Login" is specifying the location that will be used to login the user.


    Step-7 As of now we have enabled form authentication in our application but we haven't specified the resources that will be accessible to only authenticated users.

    All those controller classes that can be accessible to only authenticated users must have [Authorize] attribute in their definition. For example:

    [Authorize]
    public class SmsLogicController : Controller
    {
        public ActionResult GetData()
        {
            .......
        }
    }
    

    in this controller every action can be accessible by a user only after he/she gets authenticated else he/she will redirect to our login page that we specified in Step-6.


    Step-8 Now in our pages, we can integrate the section that will show the user login status using following markup:

    @if (Request.IsAuthenticated)
    {
        <ul>
            <li>Hello, @User.Identity.Name ! </li>
            <li>
               @using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" }))
                {
                    @Html.AntiForgeryToken()
                    <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
                }
            </li>
        </ul>
    }
    else
    {
        <ul>
            <li>Hello, Anonymous ! </li>
            <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        </ul>
    }
    

    Here we have put the "Log Off" link inside the form tag that will post the request to the "LoggOff" action inside Account controller.

    Let's create another action that will handle this request and sign out the user. The definition is as follows:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    

    It will remove the form authentication ticket from the browser and will redirect the user to the Index action inside Home contoller that may be showing any view which is accessible to all anonymous users.


    Hope this article gave you an idea of how to apply form authentication in MVC application. :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: