LoginSignup
45
43

More than 5 years have passed since last update.

Rails4アプリに対してクロスドメインでAjaxでCookieを送信したい場合

Last updated at Posted at 2014-02-18

長い前置き

最近はWebアプリケーションを開発するときにサーバ側とクライアント側のプロジェクトを分けて開発することが多い。その理由としては、最終的にはクライアント側のリソースをサーバリソースと一緒にしてデプロイするのだけど、最近はYeomanなどクライアント側の開発プロセスも複雑になってきたので分けたいためである。

サーバはRails、クライアントはYeomanを使ってJavaScriptで開発している。
ログイン認証はRails側でFacebookのOAuthを使用し、セッション情報の保持はCookieを使用している。

Railsはポート3000、クライアントはgrunt serveを使ってポート9000で実行しているのだが、JavaScriptからRailsのREST APIにリクエストを投げたときにOriginが違うのでRailsで作成したCookieが付与されないので、Rails側でセッション情報が取得できない。

ググると、jQuery.ajaxのオプションのsetCookieとかbeforeSendでsetRequestHeaderでCookieを設定できると書いてあったが、セキュリティ上出来なくなっていた。

環境

  • Rails 4.0.2
  • jQuery 1.9.1

解決方法

jQuery.ajaxの指定オプション
JavaScript側では、jQuery.ajaxのxhrField.withCredentialsオプションでtrueを設定する。

$.ajax({
  url:targetUrl,
  type:'get',
  xhrFields: {
    withCredentials: true
  }
}).done(function(data) {
  // console.log(data);
});

Rails側の対応
application.rbにクロスドメイン対応を入れる。
Access-Control-Allow-Credentialsにtrueを設定した場合はAccess-Control-Allow-Originにワイルドカードは使えない模様。

config.action_dispatch.default_headers = {
    'Access-Control-Allow-Credentials' => 'true',
    'Access-Control-Allow-Origin' => 'http://localhost:9000',
    'Access-Control-Request-Method' => '*'
}

参考資料

おしまい。

45
43
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
45
43