Ruby on Rails 4 + ActionCableを用いて下記のチャットシステムを作成しています。
<参考記事>
http://qiita.com/totzyuta/items/556d1bae65bb918db322
http://www.rubytutorial.io/actioncable-devise-authentication/
<実現したいこと>
ユーザ同士のコミュニケーションを実現したい。
基本的には1vs1のコミュニケーションで、他のユーザからは二人のやりとりは参照できないようにしたい。
<サーバ構成>
セキュアな通信を確保するためssl通信を用いています。
また、利用しているクラウドサービスのロードバランサがwss通信をサポートしていないため、
通常のアクセスはhttps通信でロードバランサに、
チャット利用時のwss通信はアプリケーションサーバに振り向けています。
なお、通常アクセスとチャット利用は下記のようにサブドメインをつけることで、
クライアント側に分別させています。
ロードバランサ → lb.example.com
アプリケーションサーバ → chat.example.com
<ActionCable周りの設定>
本仕様を実現するにあたって、必要と思われる設定ファイルのみ記述いたします。
-- クライアントサイド --
app/assets/javascripts/channels/index.coffee
coffee
1#= require cable 2#= require_self 3#= require_tree 4 5@App = {} 6App.cable = Cable.createConsumer("wss://chat.example.com:28080")
-- サーバサイド --
app/channels/application_cable/connection.rb
ruby
1module ApplicationCable 2 class Connection < ActionCable::Connection::Base 3 identified_by :current_user 4 5 def connect 6 self.current_user = find_verified_user 7 end 8 9 protected 10 def find_verified_user 11 if verified_user = User.find_by(id: cookies[:user_id]) 12 verified_user 13 else 14 reject_unauthorized_connection 15 end 16 end 17 end 18end
config/environments/initializers/session_store.rb
rails
1# Be sure to restart your server when you modify this file. 2 3Rails.application.config.session_store :cookie_store, key: '_example_session', domain: :all 4
cable/config.ru
rails
1# cable/config.ru 2require ::File.expand_path('../../config/environment', __FILE__) 3Rails.application.eager_load! 4 5require 'action_cable/process/logging' 6ActionCable.server.config.allowed_request_origins = ['lb.example.com'] 7run ActionCable.server
下記コマンドでWebSocketサーバを立ち上げています。
sh
1bundle exec puma -p 28080 cable/config.ru
<起こっている問題>
アプリケーションサーバでユーザ認証後、
cookies[:user_id] = @user.id
のような形でcookieに:user_idをセットし、同アプリケーション内であればどのアクションからも:user_idを取得することができます。
しかし、websocketの方では、以下のログの通り、:user_idがnilとなってしまい、認証ができません。
log
1Started GET "/" [WebSocket] for 126.72.113.68 at 2016-08-15 05:34:31 +0000 2 User Load (1.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` IS NULL LIMIT 1 3An unauthorized connection attempt was rejected
私の認識ですと、session_storeの設定により、サブドメインは共通のcookieを利用できると考えていたため、
このシーンで:user_idがnilと認識される理由が全く分からず困っています。
どなたかお力添えいただけませんでしょうか。
以上、よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。