Thursday, 21 July 2016

Form authentication in MVC

Tables
create table UserRole(Id int primary key identity(1,1), Name varchar(20) not null)

select * from UserRole


create table Users(ID int primary key identity(1,1), Email varchar(100), Password varchar(100), RoleId int not null foreign key references UserRole(id))

insert into Users values('tarvinder3012@gmail.com', 'test123', 1)

select * from Users



Now, Create MVC empty application

Now, In solution folder add separate project/class library for data source (Entity framework). Create database first approach and provide server detail. It will automatically create classes. Also add connection string in app config file.

You can use same connection string in your mvc project web config.

As we are going to do form authentication so we need to mention it in web config.

  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
    <authentication mode="Forms">      
    </authentication>
  </system.web>

Add controller - Account Controller

using EfModel;
using FormAuthentication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace FormAuthentication.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(Login model)
        {
            if (ModelState.IsValid)
            {
               using(TestEntities _context = new TestEntities())
               {
                   User res = _context.Users.Where(p => p.Email == model.UserName && p.Password == model.Password).FirstOrDefault();
                   if (res == null)
                   {
                       ViewBag.Status = "Invalid credentials";
                   }
                   else
                   {
                       Session["User"] = model;
                       FormsAuthentication.SetAuthCookie(res.Email, false);
                       return RedirectToAction("index", "home");
                   }
               }

               return View();
            }
            else
            {
                return new HttpNotFoundResult();
            }
        }

        [HttpGet]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("index", "account");
        }       
    }
}

Add view - Index View(Account controller)

@model FormAuthentication.Models.Login
@using System.Web.Mvc.Html

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using(Html.BeginForm("Index", "Account", FormMethod.Post))
{    
    @Html.AntiForgeryToken();
    
    <label>UserName</label>   
    @Html.TextBoxFor(u => u.UserName, new { placeholder = "Emial" });
    @Html.ValidationMessageFor(u=> u.UserName)
    
    <label>Password</label>    
    @Html.PasswordFor(u => u.Password, new { placeholder = "Password" });
    @Html.ValidationMessageFor(u=>u.Password)
    
    <input type="submit" value="Login" />

    <label>@ViewBag.Status</label>
}

Add controller - Home Controller

using FormAuthentication.Filter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FormAuthentication.Controllers
{
    [CheckAuthentication]
    public class HomeController : Controller
    {        
        public ActionResult Index()
        {
            return View();
        }
    }
}

Add view - Index View(Home controller)

@{
    ViewBag.Title = "Index";
}

<h2>Welcome</h2>

<a href="/account/logout">Logout</a>


Authorization filter - It will be use in controller to check user accessing resoureces is authorized. 

Add Class -  CheckAuthentication

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace FormAuthentication.Filter
{
    public class CheckAuthentication : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new{ controller = "account", action = "index" }));
            }
        }
    }
}








No comments:

Post a Comment