0

I have used @Html.AntiForgeryToken() in my main .cshtml page <div ng-controller="MainController as vm"> I have followed this to implement.

var headers = actionContext.Request.Headers;
                var tokenCookie = headers
                    .GetCookies()
                    .Select(c => c["__RequestVerificationToken_L21vYmlsZQ2"]) //AntiForgeryConfig.CookieName
                    .FirstOrDefault();

                var tokenHeader = string.Empty;
                if (headers.Contains("X-XSRF-Token"))
                {
                    tokenHeader = headers.GetValues("X-XSRF-Token").FirstOrDefault();
                    AntiForgery.Validate(tokenCookie != null ? tokenCookie.Value : null, tokenHeader);
                }   

@Html.AntiForgeryToken() is generating key (eg: "xyz123") while validating in OnActionExecuting() I'm getting different key (eg: "pqr678") and in AntiForgery.Validate(tokenCookie != null ? tokenCookie.Value : null, tokenHeader); getting following error

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys.

Note: I do not have a duplicate token and I also tried to add a machine key in web.config ref

ANEES
  • 300
  • 3
  • 16
  • Why you select `__RequestVerificationToken_L21vYmlsZQ2` cookie? Doesn't it suppose to be `__RequestVerificationToken`? – Will Huang Oct 26 '21 at 01:05
  • @WillHuang , In `actionContext.Request.Headers` the name is `__RequestVerificationToken_L21vYmlsZQ2`, I tried with `__RequestVerificationToken` and `AntiForgeryConfig.CookieName` but this didn't worked. – ANEES Oct 26 '21 at 09:55
  • Can you provide a sample project to GitHub so that I can understand what's the problem you are facing? – Will Huang Oct 26 '21 at 16:05

1 Answers1

0

You should use the ValidateAntiForgeryKey attribute on your action.

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)
{

}

Also, you can try to add the validationKey="AutoGenerate" on the machine config. like below:

<machineKey validationKey="AutoGenerate">
Abdus Salam Azad
  • 5,087
  • 46
  • 35