15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FuelPHPでJavascriptを使用して複数のリクエストを投げる際にCSRF対策をする。

Last updated at Posted at 2014-09-09

Security::js_fetch_token()

公式によると、AJAXでCSRFするならこれだってだいたい書いてあります。


<?= Security::js_fetch_token(); ?>

<script type="text/javascript">
function sendForm(submitButton){
    var button = $(button);
    var form = button.closest('form');

    form.append($('<input type="hidden" name="fuel_csrf_token" value="' + fuel_csrf_token() + '">'));

    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        timeout: 10000,
        complete: function(xhr, textStatus){
            // on complete
        },
        success: function(result, textStatus, xhr){
            // on success
        },
        error: function(xhr, textStatus, error){
            // on error
        }
    });
}
</script>

<form>
    <input type="text" name="foo" value="" />
    <input type="button" value="実行" onClick="sendForm(this)" />
</form>

このコード自体では動作確認をしていませんが、fuel_csrf_token()というjavascriptの関数がPHPのSecurity::js_fetch_token();によって発行されるので、それをinput hiddenに入れています。

15
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
14

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?