Troubleshooting anti-forgery token problems

前端 未结 11 2071
孤城傲影
孤城傲影 2020-11-27 03:48

I have a form post that consistently gives me an anti-forgery token error.

Here is my form:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
         


        
相关标签:
11条回答
  • 2020-11-27 04:30

    I just experienced an issue where @Html.AntiForgeryToken() was being called twice so the Anti-forger token was get screwed up in the HTTP Post payload.

    0 讨论(0)
  • 2020-11-27 04:33

    You should prevent double form submission. I prevent this type of issue using code like this:

    $('#loginForm').on('submit',function(e){
        var $form = $(this);
    
        if (!$form.data('submitted') && $form.valid()) {
          // mark it so that the next submit can be ignored
          $form.data('submitted', true);
          return;
        }
    
        // form is invalid or previously submitted - skip submit
        e.preventDefault();
    });
    

    or

    $('#loginForm').submit(function () {
        $(this).find(':submit').attr('disabled', 'disabled'); 
    });
    
    0 讨论(0)
  • 2020-11-27 04:37

    I don't know if you mean you are able to get the error on demand - or you're seeing it in your logs but in any case here's a way to guarantee an antiforgery token error.

    Wait for it...

    • Make sure you're logged out, then enter your login
    • Double click on the login button
    • You'll get :

    The provided anti-forgery token was meant for user "", but the current user is "XXX@yahoo.com".

    (For now I'm going to assume that this exact error message changed in MVC4 and that this is essentially the same message you're getting).

    There's a lot of people out there that still double click on everything - this is bad! I just figured this out after just waking up so how this got through testing I really don't know. You don't even have to double click - I've got this error myself when I click a second time if the button is unresponsive.

    I just removed the validation attribute. My site is always SSL and I'm not overly concerned about the risk. I just need it to work right now. Another solution would be disabling the button with javascript.

    This can be duplicated on the MVC4 initial install template.

    0 讨论(0)
  • 2020-11-27 04:37

    html error logger is not correct line.

    you must check all loading value in page is not null.

    0 讨论(0)
  • 2020-11-27 04:41

    AntiForgeryToken also checks your logged in user credentials haven't changed – these are also encrypted in the cookie. You can turn this off by setting AntiForgeryConfig.SuppressIdentityHeuristicChecks = true in the global.asax.cs file.

    0 讨论(0)
提交回复
热议问题