Проблема CSRF при сохранении данных в .net - PullRequest
0 голосов
/ 31 октября 2019

Когда я создаю форму в mvc с помощью токена beginform и antiforgery, а также с проверкой токена antiforgery на контроллере, но когда я сохраняю данные и локально сохраняю _requestverificationtoken, я снова формирую отправку и заменяю текущее значение токена предыдущим, а затемсохраните его и сохраните, но когда я использовал теги защиты от подделки, почему он отправляется.

                        @Html.AntiForgeryToken()
                        @Html.Hidden("PaneName", null)
                        @Html.HiddenFor(a => a.Task_Id)
                        @Html.HiddenFor(a => a.Button)
                        <div class="form-horizontal">

                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Task Details <span class="text-danger">*</span></label>

                                <div class="col-md-10">
                                    @Html.TextAreaFor(model => model.Description, new { @class = "form-control", @rows = 5, @cols = 60, @style = "max-width:65% !important;" })
                                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Additional Comments</label>

                                <div class="col-md-10">
                                    @Html.TextAreaFor(model => model.Additional_Comment, new { @class = "form-control", @rows = 5, @cols = 60, @style = "max-width:65% !important;" })
                                </div>
                            </div>*@

                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Review Date <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.EditorFor(model => model.Review_Date, new { htmlAttributes = new { @class = "form-control", placeholder = "Review Date" } })
                                    @Html.ValidationMessageFor(model => model.Review_Date, "", new { @class = "text-danger" })
                                </div>
                            </div>*@
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Weightage(%) <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.EditorFor(model => model.Weightage, new { htmlAttributes = new { @class = "form-control", placeholder = "Weightage" , onkeypress = "return isNumber(event)"} })

                                </div>
                            </div>*@
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label"> Task Assigned By </label>

                                <div class="col-sm-2">

                                    @Html.DisplayFor(a => a.TaskAssignBy)

                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Task Assign To <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.ListBoxFor(model => model.SelectedItem_js, new MultiSelectList(Model.LST_JS, "Value", "Text"), new { @id = "ddljs", @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.SelectedItem_js, "", new { @class = "text-danger" })
                                    @*@Html.ValidationMessageFor(m => m.SelectedItem_js, "", new { @class = "text-danger" })*@
                                    <br />
                                    @*@Html.ListBoxFor(model => model.SelectedItem_dir, new MultiSelectList(Model.LST_DIR, "value", "text"), new { @id = "ddldir", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(model => model.SelectedItem_ds, new MultiSelectList(Model.LST_DS, "value", "text"), new { @id = "ddlds", @class = "form-control" })
                                        @Html.ListBoxFor(model => model.SelectedItem_section_officer, new MultiSelectList(Model.LST_SECTION_OFF, "value", "text"), new { @id = "ddlsecoff", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(model => model.SelectedItem_psu, new MultiSelectList(Model.LST_PSU, "value", "text"), new { @id = "ddlpsu", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_JS, "CODE", "USER1", Model.CODE), new { @id = "ddljs", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_DIR, "CODE", "USER1", Model.CODE), new { @id = "ddldir", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_DS, "CODE", "USER1", Model.CODE), new { @id = "ddlds", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_SECTION_OFF, "CODE", "USER1", Model.CODE), new { @id = "ddlsecoff", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_PSU, "PSU_CODE", "NAME_ENGLISH", Model.CODE), new { @id = "ddlpsu", @class = "form-control" })*@

                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">PSU </label>

                                <div class="col-md-10">


                                    @Html.ListBoxFor(model => model.SelectedItem_psu, new MultiSelectList(Model.LST_PSU, "value", "text"), new { @id = "ddlpsu", @class = "form-control" })


                                </div>
                            </div>
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Priority </label>

                                <div class="col-md-10">
                                    @Html.DropDownList("Priority", new List<SelectListItem> { new SelectListItem { Text = "High", Value = "1"},
                                       new SelectListItem { Text = "Medium", Value = "2"},
                                       new SelectListItem { Text = "Low", Value = "3"}
                                       }, new { @id = "ddlpriority", @class = "form-control" })
                                </div>
                            </div>*@
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Duration Type </label>

                                <div class="col-md-10">
                                    @Html.DropDownList("Priority", new List<SelectListItem> { new SelectListItem { Text = "Short Term", Value = "1"},
                                       new SelectListItem { Text = "Long term", Value = "2"},
                                       }, new { @id = "ddlpriority", @class = "form-control" })
                                </div>
                            </div>*@
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Target Date </label>

                                <div class="col-md-10">
                                    @Html.EditorFor(model => model.DDeadline_Date, new { htmlAttributes = new { @class = "form-control", placeholder = "Deadline Date", @required = true, @id = "Deadline_Date" } })
                                </div>
                            </div>


                            <div class="form-group">

                            </div>
                            <div class="form-group">
                                <div class="col-md-offset-2 col-md-10">
                                    <input id="btnsubmit" type="submit" value="@Model.Button" class="btn btn-success sub" onclick="this.form.submit(); this.disabled = true; " />
                                </div>
                            </div>
                        </div>
                    @*}*@

                </div>



            </div>
        </div>
    </div>



</div>

    @functions{
        public string TokenHeaderValue()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;
        }
    }
    function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
    $(document).ready(function () {

        $('#btnsubmit').click(function () {
            $.ajax({
                url: '/MinuteOfMeeting/MOM',
                type: "post",
              //  contentType: "application/json",
                data: { 'Description': '12345', "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }, // JSON data goes here
                dataType: "json",
                headers: {
                    'RequestVerificationToken': '@TokenHeaderValue()'
                },
                success: function (data) {
                    alert(data);
                }
            });
        });

    });

</script>  

@model Web_App.Models.VM_MOM

@{
    ViewBag.Title = "MOM";
}
@*<link href="~/Content/bootstrap.css" rel="stylesheet" />*@
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>

<div class="container" style="min-height:560px !important; padding-bottom:20px;">

    <hr />
    <br />
    <div class="panel panel-default">

        <div class="panel-heading" style="
    background-color: #2bbbad;
    color: white;
    font-size: 19px;"><center><b>@Model.Heading</b></center></div>
        <div class="panel-body">
            <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
                <div class="panel-body">
                    @if (ViewBag.Message != null)
                    {
                        <script type="text/javascript">
                            window.onload = function () {
                                alert("@ViewBag.Message");
                            };
                        </script>
                    }
                    @*@{
                        IDictionary<string, object> attrs = new Dictionary<string, object>();
                        attrs.Add("name", "TestForm");
                        attrs.Add("id", "TestForm");
                        attrs.Add("data-asynchAction", "/Home/SendMessage");
                    }*@

                    @*@using (Html.BeginForm("MOM", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
                    {*@
                        @Html.AntiForgeryToken()
                        @Html.Hidden("PaneName", null)
                        @Html.HiddenFor(a => a.Task_Id)
                        @Html.HiddenFor(a => a.Button)
                        <div class="form-horizontal">

                            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Task Details <span class="text-danger">*</span></label>

                                <div class="col-md-10">
                                    @Html.TextAreaFor(model => model.Description, new { @class = "form-control", @rows = 5, @cols = 60, @style = "max-width:65% !important;" })
                                    @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
                                </div>
                            </div>
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Additional Comments</label>

                                <div class="col-md-10">
                                    @Html.TextAreaFor(model => model.Additional_Comment, new { @class = "form-control", @rows = 5, @cols = 60, @style = "max-width:65% !important;" })
                                </div>
                            </div>*@

                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Review Date <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.EditorFor(model => model.Review_Date, new { htmlAttributes = new { @class = "form-control", placeholder = "Review Date" } })
                                    @Html.ValidationMessageFor(model => model.Review_Date, "", new { @class = "text-danger" })
                                </div>
                            </div>*@
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Weightage(%) <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.EditorFor(model => model.Weightage, new { htmlAttributes = new { @class = "form-control", placeholder = "Weightage" , onkeypress = "return isNumber(event)"} })

                                </div>
                            </div>*@
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label"> Task Assigned By </label>

                                <div class="col-sm-2">

                                    @Html.DisplayFor(a => a.TaskAssignBy)

                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Task Assign To <span class="text-danger">*</span> </label>

                                <div class="col-md-10">

                                    @Html.ListBoxFor(model => model.SelectedItem_js, new MultiSelectList(Model.LST_JS, "Value", "Text"), new { @id = "ddljs", @class = "form-control" })
                                    @Html.ValidationMessageFor(model => model.SelectedItem_js, "", new { @class = "text-danger" })
                                    @*@Html.ValidationMessageFor(m => m.SelectedItem_js, "", new { @class = "text-danger" })*@
                                    <br />
                                    @*@Html.ListBoxFor(model => model.SelectedItem_dir, new MultiSelectList(Model.LST_DIR, "value", "text"), new { @id = "ddldir", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(model => model.SelectedItem_ds, new MultiSelectList(Model.LST_DS, "value", "text"), new { @id = "ddlds", @class = "form-control" })
                                        @Html.ListBoxFor(model => model.SelectedItem_section_officer, new MultiSelectList(Model.LST_SECTION_OFF, "value", "text"), new { @id = "ddlsecoff", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(model => model.SelectedItem_psu, new MultiSelectList(Model.LST_PSU, "value", "text"), new { @id = "ddlpsu", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_JS, "CODE", "USER1", Model.CODE), new { @id = "ddljs", @class = "form-control" })*@
                                    @*@Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_DIR, "CODE", "USER1", Model.CODE), new { @id = "ddldir", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_DS, "CODE", "USER1", Model.CODE), new { @id = "ddlds", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_SECTION_OFF, "CODE", "USER1", Model.CODE), new { @id = "ddlsecoff", @class = "form-control" })
                                        @Html.ListBoxFor(m => m.CODE, new SelectList(Model.LST_PSU, "PSU_CODE", "NAME_ENGLISH", Model.CODE), new { @id = "ddlpsu", @class = "form-control" })*@

                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">PSU </label>

                                <div class="col-md-10">


                                    @Html.ListBoxFor(model => model.SelectedItem_psu, new MultiSelectList(Model.LST_PSU, "value", "text"), new { @id = "ddlpsu", @class = "form-control" })


                                </div>
                            </div>
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Priority </label>

                                <div class="col-md-10">
                                    @Html.DropDownList("Priority", new List<SelectListItem> { new SelectListItem { Text = "High", Value = "1"},
                                       new SelectListItem { Text = "Medium", Value = "2"},
                                       new SelectListItem { Text = "Low", Value = "3"}
                                       }, new { @id = "ddlpriority", @class = "form-control" })
                                </div>
                            </div>*@
                            @*<div class="form-group">
                                <label class="col-sm-2 col-form-label">Duration Type </label>

                                <div class="col-md-10">
                                    @Html.DropDownList("Priority", new List<SelectListItem> { new SelectListItem { Text = "Short Term", Value = "1"},
                                       new SelectListItem { Text = "Long term", Value = "2"},
                                       }, new { @id = "ddlpriority", @class = "form-control" })
                                </div>
                            </div>*@
                            <div class="form-group">
                                <label class="col-sm-2 col-form-label">Target Date </label>

                                <div class="col-md-10">
                                    @Html.EditorFor(model => model.DDeadline_Date, new { htmlAttributes = new { @class = "form-control", placeholder = "Deadline Date", @required = true, @id = "Deadline_Date" } })
                                </div>
                            </div>


                            <div class="form-group">

                            </div>
                            <div class="form-group">
                                <div class="col-md-offset-2 col-md-10">
                                    <input id="btnsubmit" type="submit" value="@Model.Button" class="btn btn-success sub" onclick="this.form.submit(); this.disabled = true; " />
                                </div>
                            </div>
                        </div>
                    @*}*@

                </div>



            </div>
        </div>
    </div>



</div>
@*@section Scripts
{
    <script src="~/Scripts/App/common.js"></script>
    <script src="~/Scripts/App/antiforgery.js"></script>
}*@
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<link href="~/Content/bootstrap-multiselect.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-multiselect.js"></script>
<script type="text/javascript">
    @functions{
        public string TokenHeaderValue()
        {
            string cookieToken, formToken;
            AntiForgery.GetTokens(null, out cookieToken, out formToken);
            return cookieToken + ":" + formToken;
        }
    }
    function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
        return true;
    }
    $(document).ready(function () {
        //$('input[type=datetime]').datepicker({

        //    changeMonth: true,
        //    changeYear: true


        if ($('#Task_Id').val() != 0)
        {
            $('#Deadline_Date').datepicker({ dateFormat: 'dd/mm/yy', format: 'dd/mm/yy', minDate: 0 });
        }
        else {
            $('#Deadline_Date').datepicker({ dateFormat: 'dd/mm/yy', format: 'dd/mm/yy', minDate: 0 });
           $('#Deadline_Date').datepicker('setDate', "+7");
        }
        //});

        $('#ddlpriority').change(function ()
        {
            if($(this).val() == 1)
            {
                $('#Deadline_Date').attr("required", true);
                $('#Deadline_Date').datepicker('setDate', "+7");
            }
            else
            {
                $('#Deadline_Date').removeAttr("required");
                $('#Deadline_Date').val("");
            }

        });

        $('#Completion_Flag').click(function () {
            if ($(this).is(":checked") == true)
            {
                $('#Actual_Completion_Date').removeAttr("disabled")
            }
            else {
                $('#Actual_Completion_Date').attr("disabled", "disabled")
            }
        });
        $('#Review_Date').datepicker({ dateFormat: 'dd/mm/yy', format: 'dd/mm/yy' });
        // alert($('#Review_Date').val())
        //  $('#Review_Date').datepicker('setDate', new Date());



           //$('#Deadline_Date').datepicker('setDate', "+7");

           $('#Actual_Completion_Date').datepicker({ dateFormat: 'dd/mm/yy', format: 'dd/mm/yy' });

        //  $('#Actual_Completion_Date').datepicker('setDate', new Date());

        //$('#Review_Date').datepicker('setDate', 'today');
        $('#ddljs').multiselect({
            selectAllValue: 'multiselect-all',
            enableCaseInsensitiveFiltering: true,
            enableFiltering: true,
            maxHeight: '300',
            buttonWidth: '200',

            numberDisplayed: 2,
            nonSelectedText: 'Select Officer'
        });
        $('#ddldir').multiselect({
            selectAllValue: 'multiselect-all',
            enableCaseInsensitiveFiltering: true,
            enableFiltering: true,
            maxHeight: '300',
            buttonWidth: '200',

            numberDisplayed: 2,
            nonSelectedText: 'Select Director'
        });
        //$('#ddlds').multiselect({
        //    selectAllValue: 'multiselect-all',
        //    enableCaseInsensitiveFiltering: true,
        //    enableFiltering: true,
        //    maxHeight: '300',
        //    buttonWidth: '200',

        //    numberDisplayed: 2,
        //    nonSelectedText: 'Select Under Secretary'
        //});
        //$('#ddlsecoff').multiselect({
        //    selectAllValue: 'multiselect-all',
        //    enableCaseInsensitiveFiltering: true,
        //    enableFiltering: true,
        //    maxHeight: '300',
        //    buttonWidth: '200',

        //    numberDisplayed: 2,
        //    nonSelectedText: 'Select Section Officer'
        //});
        $('#ddlpsu').multiselect({
            selectAllValue: 'multiselect-all',
            enableCaseInsensitiveFiltering: true,
            enableFiltering: true,
            maxHeight: '300',
            buttonWidth: '400',

            numberDisplayed: 2,
            nonSelectedText: 'Select PSU'
        });
        $('#btnsubmit').click(function () {
            $.ajax({
                url: '/MinuteOfMeeting/MOM',
                type: "post",
              //  contentType: "application/json",
                data: { 'Description': '12345', "__RequestVerificationToken": $('input[name=__RequestVerificationToken]').val() }, // JSON data goes here
                dataType: "json",
                headers: {
                    'RequestVerificationToken': '@TokenHeaderValue()'
                },
                success: function (data) {
                    alert(data);
                }
            });
        });

    });

</script>  

I want that when I used already used token in it it show me error

, потому что, когда я проверяю эту страницу, она изменяет значение параметра во время выполнения и сохраняет его, сохраняя его без каких-либо проверок значения токена. когда я создаю форму в mvc с использованием токена beginform и antiforgery, а также с проверкой токена antiforgery на контроллере, но когда я сохраняю данные и локально сохраняю _requestverificationtoken, я снова формирую submit и заменяю текущее значение токена на предыдущее, затем сохраняю его такжесохранить, но когда я использовал теги защиты от подделки, почему это отправить.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...