Friday, August 23, 2019

Validate AntiForgeryToken in Dot Net CORE MVC

To validate authentication based on AntiForgeryToken in dot net CORE MVC application, perform below steps

(1) Add below line of code to Startup.cs --> ConfigureServices
services.AddMvc(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
services.AddAntiforgery(options => options.HeaderName = "Name of token in header");

(2) CSHTML: Put below line of code to view/page where we want to validate token
@Html.AntiForgeryToken()

(3) Controller Method: Put below attribute as an attribute to the method for which we want to validate token
[ValidateAntiForgeryToken]

(4) Token: once above steps get done, from your js/cshtml find token with below line of code
var token = $('[name= "__RequestVerificationToken"]').val();

(5) For ajax calls:For ajax calls put below header line of code
headers: {
                'Name of token in header': token from step-(4)
            },

Here is one reference link that I found good for me
Enable Antiforgery Token with ASP.NET Core and JQuery



No comments:

Post a Comment