Sunday, February 2, 2020

Forms Authentication in MVC

index.cshtml

@using (Html.BeginForm("index","home",FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <span>Enter Name</span>
    <input type="text" name="name"  required />

    <input type="submit"  value="Submit" />

}

HomeController.cs
        

        using System.Web.Security;

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(FormCollection formCollection)
        {

            if (ModelState.IsValid)
            {
                  var authTicket = new FormsAuthenticationTicket(
                    1,// version
                    formCollection["name"].ToString(), // user name
                    DateTime.Now, // created
                    DateTime.Now.AddMinutes(20), // expires
                    false// persistent?
                    "User"  // can be used to store roles
                    );

                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

                var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

                System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);         

                return RedirectToAction("about");

            }
            else
            {
                return View();
            }
        }

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

            return View();
        }

       
[Authorize]
        public ActionResult logout()
        {

            FormsAuthentication.SignOut();
            return RedirectToAction("index");      
       
        }


Inside the Global.asax.cs


using System.Security.Principal;
using System.Web.Security;

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie == null || authCookie.Value == "")
                return;

            FormsAuthenticationTicket authTicket;

            try
            {
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            }
            catch
            {
                return;
            }

            // retrieve roles from UserData
            string[] roles = authTicket.UserData.Split(';');

            if (Context.User != null)
                Context.User = new GenericPrincipal(Context.User.Identity, roles);

        }




Inside the web.config


  <authentication mode="Forms" >
    <forms defaultUrl="home/index" loginUrl="home/index"  protection="All"></forms>
  </authentication>

  <authorization>
    <allow users="*"/>
    <deny users="?"/>
  </authorization>

No comments:

Post a Comment

Git Commands

Git Version   To check the git version Git -v       Git Clone To clone the repository, use the following command: Git clone [u...