Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@blue-yokoyama

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

More than 1 year has passed since last update.

クロスサイト・リクエストフォージェリ(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>

1
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?