Posting to the Yii PHP framework using Backbone.js

I am trying to use the Backbone.js models to save Yii in my web application, but I get the answer โ€œCSRF Token Validation cannot be verifiedโ€ even if the model is a serialized form and I use Backbone.sync to set the title.

Model (the form has a CSRF token in it and sends it as the attribute "YII_CSRF_TOKEN"):

var v = new ModelName ($('.formclass').serializeJSON()); 

JSON Serializer:

  //form.serializeJSON (function( $ ){ $.fn.serializeJSON=function() { var json = {}; jQuery.map($(this).serializeArray(), function(n, i){ json[n['name']] = n['value']; }); return json; }; })( jQuery ); 

Backbone.sync:

 Backbone.old_sync = Backbone.sync; Backbone.sync = function(method, model, options) { var new_options = _.extend({ beforeSend: function(xhr) { console.log('backbone sync'); var token = model.get('X_CSRF_TOKEN'); console.log('token ='+token) if (token) xhr.setRequestHeader('YII_CSRF_TOKEN', token); } }, options) Backbone.old_sync(method, model, new_options); }; 

I also tried setting the header as "X_CSRF_TOKEN", but to no avail.

+6
source share
3 answers

YII_CSRF_TOKEN is not a header, it is just a form value. According to this line, our request should contain

  • CSRF cookie, it is already set by loading a page other than XHR
  • form data value named YII_CSRF_TOKEN
0
source

If you send your data using save (), you must send the cookies and session ID to the parameters. See here the cached version of this blog post (cuz is now disabled): http://webcache.googleusercontent.com/search?q=cache:tML1kmL08ikJ:blog.opperator.com/post/15671431847/backbone-js-sessions-and -authentication + & cd = 1 & hl = en & ct = clnk

0
source

If you work with localhost, you may need to configure the virtual host so that it can perform cookie authentication, as indicated in this thread: this thread

IE and Chrome do not accept cookies with localhost, so this may be the reason

0
source

Source: https://habr.com/ru/post/917641/


All Articles