LoginSignup
10
12

More than 5 years have passed since last update.

jsでRailsと通信する際の注意 Pusherでの対応

Last updated at Posted at 2012-07-11

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()
                }
            }
        });
10
12
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
10
12