Friday, July 25, 2014

FormsAuthentication in ASP.Net MVC 4

FormsAuthentication in ASP.Net MVC 4

In this blog, I am going to explain the forms authentication in asp.net mvc 4 and how to implement it in our project.

In the following example I’m going to use the Entity Framework, so if you want to learn the Entity Framework first then you can read my blog on Entity Framework here:



Step 1

First create two tables in the database named “Login” and “StudentInformation” like this:





And have some dummy data in both the tables:


Step 2

Now create an empty asp.net mvc 4 web application with razor engine and add a model class to the project named “LoginInformation” like this:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    [Table("Login")]
    public class LoginInformation
    {
        [Key]
        [Display(Name="Username")]
        [Required(ErrorMessage="Username is mandatory")]
        public string username { get; set; }

        [Display(Name="Password")]
        [Required(ErrorMessage="Password is mandatory")]
        public string password { get; set; }
    }
}


Now create another model class named “StudentInformation” like this:


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    [Table("StudentInformation")]
    public class StudentInformation
    {
        [Key] //Primary Key
        public int StudentId { get; set; }

        [Display(Name = "NAME")]
        public string Name { get; set; }

        [Display(Name = "AGE")]
        public string Age { get; set; }

        [Display(Name = "ADDRESS")]
        public string Address { get; set; }

        [Display(Name = "COURSE")]
        public string Course { get; set; }
    }
}

Step 3

Now create a DbContext class named “StudentDbContext” like this:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

namespace FormAuthenticationMvcApp.Models
{
    public class StudentDbContext : DbContext
    {
        public DbSet<StudentInformation> Student { get; set; }
        public DbSet<LoginInformation> Login { get; set; }
    }
}

Step 4

Create a connection string in the web.config like this:

<connectionStrings>
    <add name="StudentDbContext" connectionString="Data Source=DELL-PC; Initial Catalog=StudentDB; Integrated Security = true;"providerName="System.Data.SqlClient"/>
  </connectionStrings>

The important thing to notice here is that the name of the connectionString is same as the DbContext class that we have created. If we keep the name of the connectionString same as the DbContext class the corresponding DbContext class will use the connectionString to persist the data, but this is also flexible so that we have the possiblity of giving custom names to the connectionStrings.


Now add the authentication tag under the system.web tag in the web.config file like this:

<authentication mode="Forms">
    <forms loginUrl="~/Home/UserLogin" timeout="2880"></forms>
</authentication>


Step 5

Now add a controller to the project named “HomeController” and write the below in it:

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

namespace FormAuthenticationMvcApp.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        StudentDbContext context = new StudentDbContext();
       
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult UserLogin()
        {
            return View();
        }

        [HttpPost]
        public ActionResult UserLogin(LoginInformation login)
        {
            if (ModelState.IsValid)
            {
                int count = context.Login.Where(m => m.username == login.username && m.password == login.password).Count();
                if (count > 0)
                {
                    FormsAuthentication.SetAuthCookie(login.username, false);
                    return RedirectToAction("Student");
                }
            }

            return View();
        }

        [Authorize]
        public ActionResult Student()
        {
            IEnumerable<StudentInformation> student = context.Student.ToList();
            return View(student);
        }

        public ActionResult UserLogout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index");
        }

    }
}

Step 6

Now add views to the project:


Index View

@{
    ViewBag.Title = "Index";
}


<div>
    <h2>Welcome</h2>
    <br />
    @Html.ActionLink("Login","UserLogin")
</div>

UserLogin View

@model FormAuthenticationMvcApp.Models.LoginInformation

@{
    ViewBag.Title = "UserLogin";
}

<h2>Login</h2>
<br />
<div >
    @using (Html.BeginForm("UserLogin","Home", FormMethod.Post))
    {
        <fieldset>
            <legend>Login</legend>
            <div>
                @Html.LabelFor(m=>m.username)
                @Html.TextBoxFor(m=>m.username)
                @Html.ValidationMessageFor(m=>m.username)
            </div>
            <div>
                @Html.LabelFor(m=>m.password)
                @Html.PasswordFor(m=>m.password)
                @Html.ValidationMessageFor(m=>m.password)
            </div>
            <div>
                <input type="submit" value="Submit"/>
            </div>
        </fieldset>
       
    }
</div>

Student View

@model IEnumerable<FormAuthenticationMvcApp.Models.StudentInformation>

@{
    ViewBag.Title = "Student";
}

<h2>Student</h2>

<p>
    @Html.ActionLink("Logout", "UserLogout")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Age)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Course)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Age)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Course)
            </td>
        </tr>
    }

</table>

After doing all the above stuff, your solution explorer will look like this:


Output

Now run the application:



Click on Login:



Fill up the form and click on submit:





Now click on logout - it will redirect you to the index view:




Thank you for reading this article, please put your valuable comment or any suggestion/question in the comment box. 







No comments:

Post a Comment