Why multiple _RequestVerificationToken used in ASP.Net MVC

Last Reply 10 months ago By Mudassar

Posted 10 months ago

My application in mvc asp.net for database I am using sql server I had Cross-Site Request Forgery (CSRF) in my application for so I put @Html.AntiForgeryToken() in view and in controller I add [ValidateAntiForgeryToken] I am getting two RequestVerificationToken as mention in images

In View 

    <div class="login-wrapper">
        <div id="login" class="login loginpage col-lg-offset-4 col-lg-4 col-md-offset-3 col-md-6 col-sm-offset-3 col-sm-6 col-xs-offset-0 col-xs-12">
            <h1><a href="#" title="Login Page" tabindex="-1">ESH HRMS</a></h1>
            @using (Html.BeginForm("login", "admin", FormMethod.Post,new { ReturnUrl = ViewBag.ReturnUrl }))
            {
                @Html.AntiForgeryToken()
                <p>
                    <label for="user_login">
                        Username<br />
                        @Html.TextBoxFor(m => m.LoginID, new { @class = "input", @id = "txtUserName", @placeholder = "UserName", @size = "20" })
                    </label>
                </p>
                <p>
                    <label for="user_pass">
                        Password<br />
                        @Html.TextBoxFor(m => m.Password, new { @class = "input", @id = "txtPassword", type = "password", @size = "20" })

                    </label>
                </p>
                <p>
                        <div class="g-recaptcha" style="width:130%;" data-sitekey="6LdY2TMUAAAAAEmHk8ZeNF3AwdJ8D92Lm-U3LinQ"></div>

                </p>
                    <p class="forgetmenot">

                        <label class="icheck-label form-label" for="rememberme">
                            @Html.CheckBoxFor(m => m.RememberMe, new { @class = "skin-square-orange", @id = "rememberme" })
                            Remember me
                        </label>
                    </p>

                    <p class="submit">
                        <input type="submit" name="wp-submit" id="btnSubmit" class="btn btn-orange btn-block" value="Sign In" />
                    </p>
            }

            @*<p id="nav">
                <a class="pull-left" href="#" title="Password Lost and Found">Forgot password?</a>
                <a class="pull-right" href="ui-register.html" title="Sign Up">Sign Up</a>
            </p>*@


        </div>
    </div>

In Controller

   // POST: /Account/Login
   [HttpPost]
   [AllowAnonymous]
   [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        try
        {
            if (!ModelState.IsValid)
                return View(model);
            if (ValidateHuman())
            {
                string loginID = model.LoginID.ToUpper().TrimEnd();
                string password = model.Password;
                string hashedPassword = AccountManager.PassEncrypt(password);
                HRMSEntities db = new HRMSEntities();
                db.Configuration.ValidateOnSaveEnabled = false;
                db.SaveChanges();
                bool userExist = db.LetoUsers.Any(x => x.Suspend == 0 && x.Username.ToLower().TrimEnd() == loginID && x.CompanyId == Utility.CompanyID);
                if (userExist && (string.Compare(hashedPassword, db.LetoUsers.First(x => x.Suspend == 0 && x.Username.ToLower().TrimEnd() == loginID && x.CompanyId == Utility.CompanyID).Password.ToString()) == 0))
                {
                    // var user = db.LetoUsers.Where(x => x.Suspend == 0 && x.Username.ToLower().TrimEnd() == loginID && x.CompanyId == Utility.CompanyID && x.Password == hashedPassword).FirstOrDefault(); original
                   var user = db.LetoUsers.Where(x => x.Suspend == 0 && x.Username.ToLower().TrimEnd() == loginID && x.CompanyId == Utility.CompanyID).FirstOrDefault(); 
                    var emp = db.Employees.SingleOrDefault(x => x.Suspend == 0 && x.Status == 1 && x.AlternateEmployeeCode == user.EmployeeCode && x.CompanyId == Utility.CompanyID);


                    //---- Generate Authentication Ticket
                    DateTime cookieIssuedDate = DateTime.UtcNow;
                    LoggedInUser loginUser = new LoggedInUser();
                    loginUser.EmpID = Convert.ToInt32(emp.EmployeeId);
                    loginUser.UserID = user.LetoUserId;
                    loginUser.UserTypeID = Convert.ToInt32(user.UserTypeId);

                    loginUser.UserName = user.Username;

                    loginUser.EmployeeCode = user.EmployeeCode;
                    loginUser.EmployeeName = emp.FirstName;
                    //FormsAuthentication.SetAuthCookie(user.Username, model.RememberMe);
                    //Session["UserType"] = Convert.ToInt32(user.UserTypeId);
                    //Session["UserID"] = user.LetoUserId;
                    //Session["EmployeeCode"] = user.EmployeeCode;
                    //Session["UserName"] = user.Username;
                    // Getting New Guid
                    //string guid = Convert.ToString(Guid.NewGuid());
                    ////Storing new Guid in Session
                    //Session["AuthenticationToken"] = guid;
                    ////Adding Cookie in Browser
                    //Response.Cookies.Add(new HttpCookie("AuthenticationToken", guid));
                    string userData = JsonConvert.SerializeObject(loginUser);

                    var ticket = new FormsAuthenticationTicket(0,
                        model.LoginID,
                        cookieIssuedDate,
                        cookieIssuedDate.AddMinutes(30),// (model.RememberMe) ? cookieIssuedDate.AddDays(7) : cookieIssuedDate.AddMinutes(30),//FormsAuthentication.Timeout.TotalMinutes),
                        model.RememberMe,
                        userData,
                        FormsAuthentication.FormsCookiePath);


                    string encryptedCookieContent = FormsAuthentication.Encrypt(ticket);

                    var formsAuthenticationTicketCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookieContent)
                    {
                        Domain = FormsAuthentication.CookieDomain,
                        Path = FormsAuthentication.FormsCookiePath,
                        HttpOnly = true,
                        Secure = FormsAuthentication.RequireSSL
                    };

                    // ---- if remember me is checked then the cookie will expire after 7 days else at end of session
                    if (model.RememberMe)
                        formsAuthenticationTicketCookie.Expires = cookieIssuedDate.AddDays(7);

                    System.Web.HttpContext.Current.Response.Cookies.Add(formsAuthenticationTicketCookie);
                    return RedirectToAction("UserDashBoard");
                }
                else
                {
                    TempData["Error"] = "please enter correct username/password..!!";
                }
            }
            else {
                TempData["Error"] = "Incorrect Captcha..!!";
            }
        }
        catch (Exception ex)
        {

        }

        // If we got this far, something failed, redisplay form
        //ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }