The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration
Asked Answered
D

23

165

I am using Membership.create user function, then the following error is occurring,

The required anti-forgery form field "__RequestVerificationToken" is not present

How can I fix this?

Darrick answered 19/4, 2013 at 10:52 Comment(0)
C
250

You have [ValidateAntiForgeryToken] attribute before your action. You also should add @Html.AntiForgeryToken() in your form.

Crack answered 19/4, 2013 at 11:4 Comment(7)
I have a web page that has the same problem but the whole things are correct. whats the mistake.Springbok
@Springbok You should carefully check everything (fields, cookies) with fiddler and/or firebug (any browser dev tools), look at this article: asp.net/web-api/overview/security/…Crack
@Springbok me too. That is work but rarely get this error and i don't have any idea WHY?Zwieback
I have everything ok, in my tests it works, on a client's machine it worked until recently, but now it gives this error. I have no idea why. Does anybody have other ideas than the ones listed here please?Recti
Why does this even happen ? What did they invent again ?Culinarian
Html.AntiForgeryToken(); does not work !! Turning into @Html.AntiForgeryToken() worksDimitris
Here is my step-by-step approach on this issue. I am using angularJS, jquery, ASP.NET MVC 5 https://mcmap.net/q/151502/-the-required-anti-forgery-form-field-quot-__requestverificationtoken-quot-is-not-present-angularjs-mvcHolbrook
U
90

In my case, I had this in my web.config:

<httpCookies requireSSL="true" />

But my project was set to not use SSL. Commenting out that line or setting up the project to always use SSL solved it.

Ulcerous answered 28/2, 2015 at 19:56 Comment(2)
In my case the web.config had requireSSL but there were IIS bindings for both port 80 and 443, so users typing https were getting correct behaviour and users typing http were getting this error, putting in a rewrite rule to force all to https://{HTTP_HOST}/{R:1} fixed itMonotone
Thank you 😃 In my case in IIS there was this binding (https » EmptyHostName » IP » 443) but there was not a binding for (https » www.mysite.com » IP » 443). So I added a new binding with a non-empty host name for https that was equal to the domain and It solved the problem. I have rewrite settings in IIS to force http 2 https too.Popup
B
70

Like this:

The Controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MethodName(FormCollection formCollection)
{
     ...
     Code Block
     ...
}

The View:

@using(Html.BeginForm())
{
     @Html.AntiForgeryToken()
     <input name="..." type="text" />
     // rest
}
Bluefish answered 7/9, 2013 at 21:57 Comment(1)
Try using only in HTMLBluefish
J
43

Also make sure avoid not use [ValidateAntiForgeryToken] under [HttpGet].

  [HttpGet]
  public ActionResult MethodName()
  {
  ..
  }
Jodyjoe answered 24/10, 2013 at 2:44 Comment(2)
This answer complemented the others and solved my problem! ThanksBalch
This answer assumes you are not saving any submitted data (which you shouldn't be on an HttpGet). If you are, then you still need the XSRF protection that [ValidateAntiForgeryToken] provides.Mummer
A
13

You will receive the error even when Cookies are not enabled.

Auscultation answered 11/8, 2014 at 13:37 Comment(2)
Good hit. I was using Internet Explorer. Using Chrome browser solved the problem for meDimitris
This solved my problem too. enabling cookies in google chrome. ThanksBistort
S
12

Another thing that can cause this (just ran into this) is the following: if you for some reason disable all your input fields in your form. it will disable the hidden input field that holds your verification token. when the form will be posted back the token value will be missing and will generate the error that it is missing. so what you need to do is to re-enable the input field that holds the verification token and all will be well.

Setula answered 31/3, 2015 at 15:21 Comment(1)
That was my problem + solution. Thanks, great catch!Autonomic
A
10

In my case it was due to adding requireSSL=true to httpcookies in webconfig which made the AntiForgeryToken stop working. Example:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true"/>
</system.web>

To make both requireSSL=true and @Html.AntiForgeryToken() work I added this line inside the Application_BeginRequest in Global.asax

    protected void Application_BeginRequest(object sender, EventArgs e)
  {
    AntiForgeryConfig.RequireSsl = HttpContext.Current.Request.IsSecureConnection;
  }
Allyson answered 1/11, 2018 at 7:12 Comment(0)
C
8

In my case, I had this javascript on the form submit:

$('form').submit(function () {
    $('input').prop('disabled', true);
});

This was removing the hidden RequestVerificationToken from the form being submitted. I changed that to:

$('form').submit(function () {
    $('input[type=submit]').prop('disabled', true);
    $('input[type=text]').prop('readonly', true);
    $('input[type=password]').prop('readonly', true);
});

... and it worked fine.

Chesterfieldian answered 26/1, 2017 at 6:20 Comment(2)
How did you notice that anti key affected when you disabled inputs?Fagaly
@Fagaly - if you're asking how I noticed, I checked the request with fiddler and picked up that the key was not being sent. The I read that Html submits won't include disabled controls. So I changed it to readonly and excluded the hidden controls. Seems to work nicely.Chesterfieldian
O
8

Another possibility for those of us uploading files as part of the request. If the content length exceeds <httpRuntime maxRequestLength="size in kilo bytes" /> and you're using request verification tokens, the browser displays the 'The required anti-forgery form field "__RequestVerificationToken" is not present' message instead of the request length exceeded message.

Setting maxRequestLength to a value large enough to cater for the request cures the immediate issue - though I'll admit it's not a proper solution (we want the user to know the true problem of file size, not that of request verification tokens missing).

Oakman answered 4/2, 2018 at 0:15 Comment(0)
C
6

Make sure in your controller that you have your http attribute like:

[HttpPost]

also add the attribute in the controller:

[ValidateAntiForgeryToken]

In your form on your view you have to write:

@Html.AntiForgeryToken();

I had Html.AntiForgeryToken(); without the @ sign while it was in a code block, it didn't give an error in Razor but did at runtime. Make sure you look at the @ sign of @Html.Ant.. if it is missing or not

Crowe answered 18/1, 2017 at 15:38 Comment(0)
F
4

If anyone experiences the error for the same reason why I experience it, here's my solution:

if you had Html.AntiForgeryToken();

change it to @Html.AntiForgeryToken()

Fitting answered 14/9, 2016 at 17:0 Comment(0)
C
4

Got this error in Chrome with default login for ASP.NET with Individual User Accounts

.cshtml:

@using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Use a local account to log in.</h4>

Controller:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)

Solved by clearing site data for the site:

enter image description here

Completion answered 17/11, 2019 at 18:47 Comment(2)
Ok its worked. But this happening again and again. In Firefox same project is running properly. What can I do?Lewert
@CanÜrek Do you have several different projects/sites with the same domain? Ex localhost, app.site.com and app2.site.com etc? It normally happens because of this.Completion
H
3

In my case incorrect domain in web.config for cookies was the reason:

<httpCookies domain=".wrong.domain.com" />
Huston answered 7/7, 2015 at 12:29 Comment(1)
yeep! if you on local computer type <httpCookies domain="localhost" /> then only on local computer cookies will work and if you try to open your site on other machine you will enter it's ip (f.e. 192.168.1.43) that will not work becase it looking for "localhost"Tatter
M
1

All the other answers in here are also valid, but if none of them solve the issue it is also worth checking that the actual headers are being passed to the server.

For example, in a load balanced environment behind nginx, the default configuration is to strip out the __RequestVerificationToken header before passing the request on to the server, see: simple nginx reverse proxy seems to strip some headers

Marimaria answered 24/4, 2018 at 3:17 Comment(0)
F
0

In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.

Forthright answered 23/2, 2017 at 16:9 Comment(0)
H
0

i'd like to share mine, i have been following this anti forgerytoken tutorial using asp.net mvc 4 with angularjs, but it throws an exception everytime i request using $http.post and i figured out the solution is just add 'X-Requested-With': 'XMLHttpRequest' to the headers of $http.post, because it seems like the (filterContext.HttpContext.Request.IsAjaxRequest()) does not recognize it as ajax and here is my example code.

App.js

var headers = { 'X-Requested-With': 'XMLHttpRequest', 'RequestVerificationToken': $scope.token, 'Content-Type': 'application/json; charset=utf-8;' };

$http({ method: 'POST', url: baseURL + 'Save/User', data: JSON.stringify($scope.formData), headers: headers }).then(function (values) { alert(values.data); }).catch(function (err) { console.log(err.data); });


SaveController

[HttpPost] [MyValidateAntiForgeryToken] public ActionResult User(UserModel usermodel) { ....

Hopeless answered 12/7, 2017 at 1:3 Comment(0)
P
0

Because this comes up with the first search of this:

I had this issue only in Internet Explorer and couldnt figure out the what the issue was. Long story short it was not saving the cookie portion of the Token because our (sub)domain had an underscore in it. Worked in Chrome but IE/Edge didnt not like it.

Paraphrast answered 29/8, 2017 at 17:32 Comment(0)
H
0

Sometimes you are writing a form action method with a result list. In this case, you cannot work with one action method. So you have to have two action methods with the same name. One with [HttpGet] and another with [HttpPost] attribute.

In your [HttpPost] action method, set [ValidateAntiForgeryToken] attribute and also put @Html.AntiForgeryToken() in your html form.

Hyohyoid answered 30/1, 2019 at 8:20 Comment(0)
D
0

In my case I was getting this error while making an AJAX post, it turned out to be that the __RequestVerificationToken value wasn't being passed across in the call. I had to manually find the value of this field and set this as a property on the data object that's sent to the endpoint.

i.e.

data.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();

Example

HTML

  <form id="myForm">
    @Html.AntiForgeryToken()

    <!-- other input fields -->

    <input type="submit" class="submitButton" value="Submit" />
  </form>

Javascript

$(document).on('click', '#myForm .submitButton', function () {
  var myData = { ... };
  myData.__RequestVerificationToken = $('#myForm input[name="__RequestVerificationToken"]').val();

  $.ajax({
    type: 'POST',
    url: myUrl,
    data: myData,
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    dataType: 'json',
    success: function (response) {
      alert('Form submitted');
    },
    error: function (e) {
      console.error('Error submitting form', e);
      alert('Error submitting form');
    },
  });
  return false; //prevent form reload
});

Controller

[HttpPost]
[Route("myUrl")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyUrlAsync(MyDto dto)
{
    ...
}
Durr answered 1/7, 2019 at 9:34 Comment(3)
In fact if you ll define the structure of your MyDto class then it will be very helpfulCrystallize
Well I'm not sure it will actually be very helpful and the example code is long gone now, so let's say public class MyDto { public bool Whatever { get; set; } }Durr
It all depends on how you preparing myData. If you are doing myData=$('myForm').serialize() it should work just fine.Sheeran
R
0

I have solved it this way

[AttributeUsage(AttributeTargets.Method)]
public class ExcludeFromAntiForgeryValidationAttribute : Attribute{
}

and place System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, formToken) in if condition

bool shouldValidate =!filterContext.ActionDescriptor.GetCustomAttributes(typeof(ExcludeFromAntiForgeryValidationAttribute), true).Any();
if (shouldValidate){
    System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, formToken);
}
Rafiq answered 25/8, 2021 at 8:15 Comment(0)
A
0

For me it was a missleading error related to asp.net and the limit on the request body size. I was happening only when trying to submit files more than 4MB. Adding explicitely the desired size in the web.config resolved the error:

<httpRuntime targetFramework="4.7.1" maxRequestLength="10096" />

ASP.NET Request Limits: http://msdn.microsoft.com/en-us/library/e1f13641.aspx IIS Request Limits: http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits

Allium answered 28/3, 2023 at 17:20 Comment(0)
S
0

In my case, my web.config did not have httpCookies tag. I didn't suspect to cause any issues initially but specifically adding <httpCookies requireSSL="false" domain="mydomain.com" /> resolved the error.

Snatchy answered 31/1 at 7:52 Comment(0)
M
-1

If you want to use [ValidateAntiForgeryToken] on a method you should just add @Html.AntiForgeryToken() to the form which is using the method mentioned.

If you have the method with the same name of the View(which has the form with @Html.AntiForgeryToken() ) then you should have two overloaded method in the controller.

Something like this:

First-> for the ActionResult for the view

[AllowAnonymous]
public ActionResult PasswordChange()
{
   PasswordChangeViewModel passwordChangeViewModel = new PasswordChangeViewModel();
   return View(passwordChangeViewModel);
}

Second-> for the HttpPost method

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult PasswordChange(PasswordChangeViewModel passwordChangeViewModel)
{
   //some code
} 
Marchak answered 17/2, 2022 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.