How to prevent Cross-Site Request Forgery attacks in ASP.NET Core.
SolutionCreate an empty project and update Startup to add middleware and services for MVC,
- public class Startup
- {
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddSingleton<IMovieService, MovieService>();
- services.AddMvc();
- }
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseMvcWithDefaultRoute();
- }
- }
Create a model and service,
- public class Movie
- {
- public string Title { get; set; }
- }
- public interface IMovieService
- {
- List<Movie> GetMovies();
- void AddMovie(Movie item);
- }
Note - The implementation of the service doesn’t matter here but it can be getting data from EF etc. In the sample, I just stored data in-memory.
Add a Controller.
- public class HomeController : Controller
- {
- private readonly IMovieService service;
- public HomeController(IMovieService service)
- {
- this.service = service;
- }
- public IActionResult Index()
- {
- var model = this.service.GetMovies();
- return View(model);
- }
- public IActionResult Create()
- {
- return View();
- }
- [HttpPost]
- [ValidateAntiForgeryToken]
- public IActionResult Save(Movie model)
- {
- this.service.AddMovie(model);
- return RedirectToAction("Index");
- }
- }
Add an Index View.
- @using Fiver.Security.Csrf.Models.Home
- @model List<Movie>
- <strong>Home</strong>
- <a asp-action="Create">Create</a>
- <ul>
- @foreach (var item in Model)
- {
- <li>@item.Title</li>
- }
- </ul>
Add a Create view.
- @using Fiver.Security.Csrf.Models.Home
- @model Movie
- <strong>Create</strong>
- <form asp-action="Save" method="post">
- <label asp-for="Title"></label>
- <input asp-for="Title" /> <br />
- <br />
- <button type="submit">Save</button><br />
- </form>
Run and browse to Create view and observe its source.
- <strong>Create</strong>
- <form method="post" action="/Home/Save">
- <label for="Title">Title</label>
- <input type="text" id="Title" name="Title" value="" /> <br />
- <br />
- <button type="submit">Save</button><br />
- <input name="__RequestVerificationToken" type="hidden" value="CfDJ8N-xGVhsz-FFuPUED-HLkPE1W4kY7t4IBowqElti5j6zVsXpONu4D8nZ6wdM50tq-X-Y-hA-gPBiXcxzpBmhgxGmzcJSX6Aopc239-js0cPwQv0jZK-l5pY8Z9EZHFC_LCdp2VO3pCp1PKy8D_-T_C8" />
- </form>




Tridip BhattacharjeePosted Jan 16, 2018, 6:09 AM
@Html.AntiForgeryToken() is not available in asp.net core ?
Tridip BhattacharjeePosted Jan 16, 2018, 6:04 AM
I saw your fiddler works with localhost but when i try to capture localhost by fiddler then mine does not. what setting you done for fiddler?
Arvind SinghPosted Jan 12, 2018, 10:46 PM
Good one............