RailsではデフォルトでCSRF攻撃対策がされていて、jsで何も考えずにget以外のmethod(postなど)で通信するとsessionが無効化される。
このため、追加でauthenticity_tokenを送る必要がある。
CSRF攻撃対策
controllers/application_controller.rb
protect_from_forgery
上記のようにデフォルトで表記されていて、全てのアクションにCSRF攻撃対策されている。
protect_from_forgery :except => ["create"]
protect_from_forgery :only => ["create"]
など、対策したいアクションを指定することもできる。
参考
CSRFトークンの検証プロセス
CSRFの対応について、rails使いが知っておくべきこと
js
対策されているアクションとget以外で通信する際には、meta情報にあるauthenticity_tokenを追加して送る必要がある。
今回はjQueryで取得して送信する。
hoge.js
$.post(
'/hoge/action',{
"hoge":hoge,
"authenticity_token":getCSRFtoken()
});
function getCSRFtoken(){
return $("meta[name=csrf-token]").attr("content");
}
Pusher
Pusherでpush通信する際は、以下のようにpusher.jsの通信部分を書き換える必要がある。
pusher.js
b.send("socket_id="+encodeURIComponent(a.connection.socket_id)+"&channel_name="+encodeURIComponent(this.name)+"&authenticity_token="+getCSRFtoken())
追記
pusherのバージョンが古かったようです。
v1.12.1では以下のようにソケットを作ると解決します。
hoge.js
var socket = new Pusher(PUSHER_KEY,{
auth: {
headers: {
'X-CSRF-Token': getCSRFtoken()
}
}
});