Programing

필수 위조 방지 양식 필드 "__RequestVerificationToken"이 없습니다. 사용자 등록 오류

lottogame 2020. 6. 27. 10:57
반응형

필수 위조 방지 양식 필드 "__RequestVerificationToken"이 없습니다. 사용자 등록 오류


Membership.create사용자 기능을 사용 하고 있는데 다음 오류가 발생합니다.

필수 위조 방지 양식 필드 "__RequestVerificationToken"이 없습니다.

이 문제를 어떻게 해결할 수 있습니까?


당신은 [ValidateAntiForgeryToken]행동하기 전에 속성이 있습니다. 또한 @Html.AntiForgeryToken()양식에 추가해야합니다 .


필자의 경우 web.config 에이 기능이 있습니다.

<httpCookies requireSSL="true" />

그러나 내 프로젝트는 SSL을 사용하지 않도록 설정되었습니다. 해당 라인을 주석 처리하거나 항상 SSL을 사용하도록 프로젝트를 설정하면 해결되었습니다.


이처럼 :

컨트롤러

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

보기:

@using(Html.BeginForm())
{
     @Html.AntiForgeryToken()
     <input name="..." type="text" />
     // rest
}

또한 [HttpGet] 아래의 [ValidateAntiForgeryToken]을 사용하지 마십시오.

  [HttpGet]
  public ActionResult MethodName()
  {
  ..
  }

쿠키가 활성화되지 않은 경우에도 오류가 발생합니다.


이 문제를 일으킬 수있는 또 다른 것은 다음과 같습니다. 어떤 이유로 든 양식에서 모든 입력 필드를 비활성화하십시오. 확인 토큰을 보유한 숨겨진 입력 필드를 비활성화합니다. 양식이 다시 게시되면 토큰 값이 누락되고 누락 된 오류가 생성됩니다. 따라서 확인 토큰을 보유한 입력 필드를 다시 활성화하면 모든 것이 잘됩니다.


요청의 일부로 파일을 업로드하는 사람들에게 또 다른 가능성. 콘텐츠 길이가 초과 <httpRuntime maxRequestLength="size in kilo bytes" /> 하고 요청 확인 토큰을 사용하는 경우 브라우저는 'The required anti-forgery form field "__RequestVerificationToken" is not present'요청 길이 초과 메시지 대신 메시지를 표시합니다 .

maxRequestLength를 요청에 맞게 충분히 큰 값으로 설정하면 즉각적인 문제가 해결되지만 적절한 해결책이 아니라는 점을 인정할 것입니다 (사용자는 요청 확인 토큰이 아닌 파일 크기의 실제 문제를 사용자가 알기를 원합니다).


제 경우에는 제출 양식 에이 자바 스크립트가 있습니다.

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

제출 된 양식에서 숨겨진 RequestVerificationToken을 제거했습니다. 나는 그것을 다음과 같이 바꿨다.

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

... 그리고 잘 작동했습니다.


컨트롤러에서 http 속성이 다음과 같은지 확인하십시오.

[HttpPost]

또한 컨트롤러에 속성을 추가하십시오.

[ValidateAntiForgeryToken]

당신의 관점에서 당신은 다음과 같이 작성해야합니다.

@Html.AntiForgeryToken();

나는 Html.AntiForgeryToken (); 코드 블록에있는 동안 @ 기호가 없으면 Razor에서 오류가 발생하지 않지만 런타임에 수행되었습니다. @ Html.Ant.의 @ 기호가 없는지 확인하십시오.


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()


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

<httpCookies domain=".wrong.domain.com" />

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;
  }

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.


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.


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


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.


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)
    {
        ...
    }

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) { ....

참고URL : https://stackoverflow.com/questions/16102957/the-required-anti-forgery-form-field-requestverificationtoken-is-not-present

반응형