4
1

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.

【JavaScript】「CSRF token mismatch.」の回避方法

Last updated at Posted at 2019-10-05

クロスサイト・リクエストフォージェリ(CSRF)トークンとは

簡単に言うと許可するリクエストの証明的なもの。

ということで開発中にjavaScripでPOST送信しようとしたときに「CSRF token mismatch.」のエラーが出たときの対処方法。

javascript

function hoge(value) {
    // form作成
    var form = document.createElement('form');
    // 送信先のURL
    form.action = '/sample/url/';
    // HTTPメソッドはここで指定
    form.method = 'POST';

    // hiddenで引数の値を送信する。
    var send_value = document.createElement('input');
    send_value.type = 'hidden';
    send_value.name = 'key';
    send_value.value = value;
    form.appendChild(send_value);

    // ここからCSRFトークンを送信準備
    var csrf = document.createElement('input');
    // すでに存在しているname="csrf-token"のvalueの値を取得する。
    var token = document.getElementsByName('csrf-token').value;
    csrf.type = 'hidden';
    csrf.name = 'csrf-token';
    csrf.value = token;
    form.appendChild(csrf);
    
    // 送信!
    form.submit();
}

HTML

<a href="#" onclick="hoge('CSRF突破!!')"></a>

<form name="csrf-token" value="1234567890" ></form>

4
1
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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?