Sunday, February 26, 2017

Forms Authentication in Asp.Net MVC 5

In this post I will show you how to Create FormsAuthentication in Asp.Net MVC 5.
Previously I had shown How to....
MVC:
Output:

AngularJS:
Create UserController using users table.
  

    public class UsersController : Controller
    {
        // GET: Users
        public ActionResult login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult login(User usr)
        {
            using (EmployeeDBEntities ent = new EmployeeDBEntities())
            {
                var usrCount = ent.Users.Where(x => x.Name == usr.Name && x.Password == usr.Password).ToList().Count();
                if (usrCount > 0)
                {
                    FormsAuthentication.SetAuthCookie(usr.Name, false);
                    TempData["LoginName"] = usr.Name;
                    if (Request.UrlReferrer.Query.Contains("ReturnUrl"))
                    {
                        return RedirectToAction("Index", Request.UrlReferrer.Query.Replace("?ReturnUrl=%2f", ""));
                    }
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return View("login");
                }
            }
        }

        public ActionResult logout()
        {
            FormsAuthentication.SignOut();
            TempData["LoginName"] = null;
            return Redirect("login");
        }
    }

Now ADD View for login, It looks as shown
  

@model FormsAuthDemo.Models.User

@{
    ViewBag.Title = "login";
}

<h2>login</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>User</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.PasswordFor(model => model.Password, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Login" class="btn btn-default" />
            </div>
        </div>
    </div>
}

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

Now in the web.config, within system.web tag
  

<system.web>    
    <authentication mode="Forms">
      <forms loginUrl="/users/login"></forms>
    </authentication>
</system.web>

In EmployeeController use Authorize attribute at controller level.
In the Home/Index.cshtml page Add the below code
  

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    @if (TempData["LoginName"] != null)
    {
        <h1>Welcome @TempData["LoginName"]</h1>
        @Html.ActionLink("LogOut","logout","users")
    }
    else
    {
        <h1>Welcome Guest</h1>
        @Html.ActionLink("LogIn","login","users")
    }
</div>

Download the entire Code from HERE

No comments:

Post a Comment