1.5.4.Anti-forgery Tokens

  • Malicious page:

    • If the hacker put image or IFrame and write a little bit JavaScript code, when the page is loaded, it will send HTTP request to our endpoint

    • If user has an active session on our wibsite, these requests will be successfully executed on his behalf.

  • CSRF (Cross-Site Request Forgery)

  • 2 step to prevent:

    • 1.Add in client form

      @Html.AntiForgeryToken()
    • 2.Add in controller to validate

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new CustomerFormViewModel
                {
                    customer = customer,
                    MembershipTypes = _context.membershipType.ToList()
                };
                return View("CustomerForm", viewModel);
            }
      
            if (customer.Id == 0)
            {
                _context.Customers.Add(customer);
            }
            else
            {
                var customersInDb = _context.Customers.Single(c => c.Id == customer.Id);
      
                customersInDb.Name = customer.Name;
                customersInDb.Birthday = customer.Birthday;
                customersInDb.membershipTypeId = customer.membershipTypeId;
                customersInDb.IsSubscribeToNesletter = customer.IsSubscribeToNesletter;
            }
            _context.SaveChanges();
            return RedirectToAction("Index", "Customers");
        }

Last updated