# 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");
      }
    ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jen-hsuan-hsieh.gitbook.io/asp-net/chapter1/1.1.the-complete-asp.net-mvc-5-course/15implement-validation/154anti-forgery-tokens.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
