KMVC and anti-forgery token

234 views
Skip to first unread message

Pawel

unread,
Feb 18, 2015, 4:02:56 AM2/18/15
to knocko...@googlegroups.com
Hi everyone,
Is there a nice way to send MVC's anti-forgery tokens using kmvc?

Using pure razor it would look like this in my view:
@using (Html.BeginForm())
{
   
@Html.AntiForgeryToken()
// Description of forms for my model  
//....
//....

}


and then I would put  [ValidateAntiForgeryToken] tag in controller action
[HttpPost]
[ValidateAntiForgeryToken]
       
public ActionResult Create(Template template)
       
{
         
//some logic
         
//....

           
return View(template);
       
}

but how to do this using knockout mvc and its helpers?

Ian Klek

unread,
Jan 11, 2016, 9:28:23 AM1/11/16
to Knockout MVC
Sadly, it appears this is where KMVC fails. It's simple enough to return the token in the property __RequestVerificationToken, but i don't think it will validate as the ajax callback content type needs to be "application/x-www-form-urlencoded". I have no idea how you would override this.

Maybe someone could help?

Cheers

Ian

Ian Klek

unread,
Jan 12, 2016, 4:48:18 AM1/12/16
to Knockout MVC
I found a way to get it working...

You can't use the KMVC approach though, you must add a custom save method to your viewModel. Mine is like this:

viewModel.Save = function () {


           
var url = $('#frmSave').attr('action');
           
var token = $("input[name='__RequestVerificationToken']").val();


            knockoutExtensions
.KnockoutSaveWithAntiForgeryToken(url, viewModel, token);          


       
}


(function (m, $) {


    m
.KnockoutSaveWithAntiForgeryToken = function (url, model, token) {


       
var submitData = ko.mapping.toJSON(model);
       
var submitObj = JSON.parse(submitData);
        submitObj
["__RequestVerificationToken"] = token;

        $
.ajax({
            url
: url,
            type
: 'POST',
            data
: submitObj,
            contentType
: "application/x-www-form-urlencoded",
            success
: function (data) {
               
if (data.redirect) {
                    location
.href = resolveUrl(data.url);
               
}
               
else {
                    ko
.mapping.fromJS(data, model);
               
}
           
},
            error
: function (error) {
                alert
("There was an error posting the data to the server: " + error.responseText);
           
}
       
});


   
}




}(window.knockoutExtensions = window.knockoutExtensions|| {}, jQuery));



On Wednesday, 18 February 2015 09:02:56 UTC, Pawel wrote:
Reply all
Reply to author
Forward
0 new messages