Bulknews::Subtech RSSフィード

2008/09/18 (木)

[jQuery] add CSRF token automatically 18:06  [jQuery] add CSRF token automatically - Bulknews::Subtech を含むブックマーク はてなブックマーク -  [jQuery] add CSRF token automatically - Bulknews::Subtech

Automatically add session_token to A and FORM tags with class="requires-token". You can validate the token in the backend to prevent CSRF attacks. Token can be anything you want, but using SHA1 hex of session ID etc. would be reasonable to implement.

$(function(){
   if (Framework.session_token) {
    $("form.requires-token").each(function() {
      var el = $(document.createElement('input'));
      el.attr('type', 'hidden');
      el.attr('name', 'session_token');
      el.val(Framework.session_token);
      $(this).append(el);
    });
    $("a.requires-token").each(function (e){
      var el = $(this);
      var prefix = el.attr('href').match(/\?/) ? "&" : "?";
      el.attr('href', el.attr('href') + prefix + 'session_token=' + Framework.session_token);
      if (el.attr('title')) {
        el.click(function(){
          if (!confirm(el.attr('title'))) return false;
        });
      }
    });
  }
});

If A tag has @title attribute, onclick handler would prompt that to confirm the action, which might be useful to implement "delete" links with A tags.