What is the Html.AntiForgeryToken helper function for?

后端 未结 5 955
遥遥无期
遥遥无期 2021-02-05 18:51

Can somebody tell me more details about it?

5条回答
  •  太阳男子
    2021-02-05 19:17

    Well today, we will look at a type of security breach in a web application that is called Cross Site Request Forgery or CSRF hack. CSRF is the lesser known cousin of XSS.Cross Site Request forgery is a type of a hack where the hacker exploits the trust of a website on the user.

    The easy way to do this is to use the ValidateAnitForgery token attribute in the ProductDetails post action method as follows

    [HttpPost]
    [Authorize(Roles = "Admins")]
    [ValidateAntiForgeryToken()]
    public ActionResult Edit(ProductDetails productdetails)
    {
      if (ModelState.IsValid)
      {
        db.Entry(productdetails).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
     }
     return View(productdetails);
    }
    

    To generate the AntiForgeryToken and the Cookie on the client side, we declare it as follows in the HTML form in the Edit.cshtml

    @using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    @Html.AntiForgeryToken()
    
    ProductDetails

    This ensures that a form being posted to the server was actually generated by the same server. Thus fake forms that do not have the AntiForgeryToken from the correct server, gets rejected.

    Also refer the simple example here

    https://github.com/devcurry/mvc101-anti-forgery-token

提交回复
热议问题