2016-09-11 127 views
6

我有一個連接到網絡套接字的問題。有一個錯誤:ActionCable - 無法升級到WebSocket

Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket) 
    User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT ? [["LIMIT", 1]] 
An unauthorized connection attempt was rejected 
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket) 
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-09-11 18:57:49 +0200 
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2016-09-11 18:57:49 +0200 

connection.rb

module ApplicationCable 
    class Connection < ActionCable::Connection::Base 
    identified_by :current_user 

    def connect 
     self.current_user = find_verified_user 
     logger.add_tags 'ActionCable', "User #{current_user.id}" 
    end 

    protected 

    def find_verified_user 
     if verified_user = User.find_by(id: cookies.signed[:user_id]) 
     verified_user 
     else 
     reject_unauthorized_connection 
     end 
    end 
    end 
end 

我找到了一些解決方案,我應該使用config.allowed_request_origins,但它並沒有解決我的問題。我試着用session_helper加入這個方法:

def set_cookie(user) 
    the_username = user.username.to_s 
    cookies.permanent.signed[:username] = the_username 
end 

沒有修復我的問題。

更新: 我看到問題是cookie.signed [:user_id]爲零。你有什麼建議可以解決這個問題的原因?我使用標準的URL和端口進行測試(localhost:3000)。

回答

6

我使用env['warden'].user解決了我的問題。以下是更新的方法。

def find_verified_user 
     (current_user = env['warden'].user) ? current_user : reject_unauthorized_connection 
    end 
+3

這還不夠。這樣,您只需在用戶登錄時刪除錯誤。但如果用戶未登錄 - **錯誤仍然存​​在**。這是因爲「room.coffee」中的App.room = App.cable.subscriptions.create「RoomChannel」'call'(或類似於你的代碼)。解決方法是根據用戶是否登錄來有條件地呈現'room.coffee',但這需要從資產中排除'room.coffee' - 並單獨呈現(因爲您無法有條件地呈現js if用戶登錄/退出)。 – prograils