从AntiForgeryToken()获取原始值(不是html)

eva*_*nal 5 .net c# asp.net-mvc csrf asp.net-mvc-3

这个美丽的抽象让你放在@Html.AntiForgeryToken()cshtml文件中,这个文件被神奇地扩展到类似的东西;

<input name="__RequestVerificationToken" type="hidden" value="JjMHm5KJQ/qJsyC4sgifQWWX/WmADmNvEgHZXXuB07bWoL84DrmQzE6k9irVyFSJ5VSYqeUIXgl4Dw4NHSotLwflGYTyECzLvrgzbtonxJ9m3GVPgUV7Z6s2Ih/klUB78GN7Fl4Gj7kxg62MEoGcZw175eVwTmkKJ0XrtEfD5KCVvYIMHNY8MT2l+qhltsGL87c9dII42AVoUUQ2gTvfPg==" />
Run Code Online (Sandbox Code Playgroud)

在页面提供之前通过mvc.但是我的页面有一些JavaScript进行ajax调用,即使它被添加到表单中也不包括令牌.他们目前正在获得预期,[HttpAntiForgeryException]: A required anti-forgery token was not supplied or was invalid.因为他们没有令牌.我知道我可以解析DOM中的值,但我不应该这样做.是否有其他方式来获取/获取此值?要清楚,我的意思是我想要一个方法的重载,它只返回值作为字符串或某种具有名称和值的对象.

为了提供更多的上下文我的表单和相关的JS看起来有点像这样;

<form action="/settings" method="post"><input name="__RequestVerificationToken" type="hidden" value="JjMHm5KJQ/qJsyC4sgifQWWX/WmADmNvEgHZXXuB07bWoL84DrmQzE6k9irVyFSJ5VSYqeUIXgl4Dw4NHSotLwflGYTyECzLvrgzbtonxJ9m3GVPgUV7Z6s2Ih/klUB78GN7Fl4Gj7kxg62MEoGcZw175eVwTmkKJ0XrtEfD5KCVvYIMHNY8MT2l+qhltsGL87c9dII42AVoUUQ2gTvfPg==" />    <fieldset>
        <h3>User Settings</h3>
        <ul>
            <li>
            label for="password">Password</label>
                <a href="#" id="change_password" class="changePasswordButton">Edit</a>
                <div id="password_section" class="inlineedit">
                    <div>
                        <span for="existing_password">Current password</span> <input autocomplete="off" class="required" id="existing_password" name="existing_password" type="password" />
                    </div>
                    <div>
                        <span for="new_password">New password</span> <input autocomplete="off" class="required" id="new_password" name="new_password" type="password" />
                        <span id="password_strength" />
                    </div>
                    <div>
                        <span for="confirm_password">Confirm password</span> <input autocomplete="off" class="required" id="confirm_password" name="confirm_password" type="password" />
                    </div>
                    <div class="inlinesave">
                        <input type="button" value="Change" onclick="onPostChangePassword();"/>
                        <a href="#" id="cancel_password" class="cancel">Cancel</a>
                    </div>
                </div>
            </li>
    // a bunch more of these that call their own onPostChangeSetting method
Run Code Online (Sandbox Code Playgroud)

onPostChangePassword() 然后做一些输入验证;

 if(validPWD && validNewPWD && validConfirmPWD && current_pwd != new_pwd){
                        // Post the password change
                        var currentAjaxRequest = $.ajax({
                            type: "POST",
                            url: "/settings/preferences/changepassword",
                            cache: false,
                            data: {password: $('#new_password').val(), current: $('#existing_password').val(),confirm: $('#confirm_password').val()},
                            success: password_success,
                            error: password_error,
                            dataType: "json"
                        });
                        return true;
                  }
Run Code Online (Sandbox Code Playgroud)

理想情况下(因为这是cshtml文件中的逐字)将被修改为这样的东西;

data: {password: $('#new_password').val(), current: $('#existing_password').val(),confirm: $('#confirm_password').val(),
__RequestVerificationToken:@Html.AntiForgeryValue() }
Run Code Online (Sandbox Code Playgroud)

tl; dr是否有办法在AntiForgeyToken变成一串html之前与之交互?

stu*_*rtd 7

您可以使用这样的代码(例如_Layout.cshtml)将AntiForgery标头添加到所有Ajax POST请求中,或者您可以根据特定请求对其进行调整.(代码假设您使用的是jQuery)

@functions{
    private static string TokenHeaderValue()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;
    }
}

<script type="text/javascript">
    $(document).ajaxSend(function (event, jqxhr, settings) {
        if (settings.type == "POST") {   
            jqxhr.setRequestHeader('@ValidateHttpAntiForgeryTokenAttribute.RequestVerificationTokenName',
                                   '@TokenHeaderValue()');
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在服务器端进行这些Ajax调用,然后您需要调用带有cookie和表单标记的AntiForgery.Validate的重载,您可以通过将此属性添加到通过Ajax调用的操作方法(显式地或通过父控制器)来启用它,或通过过滤器)

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class,
                AllowMultiple = false, Inherited = true)]
public sealed class ValidateHttpAntiForgeryTokenAttribute 
                                 : FilterAttribute, IAuthorizationFilter

{
    public const string RequestVerificationTokenName = "RequestVerificationToken";

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            ValidateRequestHeader(filterContext.HttpContext.Request);
        }
        else
        {
            AntiForgery.Validate();
        }
    }

    private static void ValidateRequestHeader(HttpRequestBase request)
    {
        string cookieToken = string.Empty;
        string formToken = string.Empty;

        var tokenValue = request.Headers[RequestVerificationTokenName];

        if (string.IsNullOrEmpty(tokenValue) == false)
        {
            string[] tokens = tokenValue.Split(':');

            if (tokens.Length == 2)
            {
                cookieToken = tokens[0].Trim();
                formToken = tokens[1].Trim();
            }
        }

        AntiForgery.Validate(cookieToken, formToken);
    }
Run Code Online (Sandbox Code Playgroud)