如何更改此代码以连接到不需要身份验证的频道,同时仍允许在某些频道上进行身份验证?
phoenix.js:701 WebSocket 连接到 'ws://localhost:4000/socket/websocket?token=&vsn=1.0.0' 失败:WebSocket 握手期间出错:意外响应代码:403
user_socket.ex
defmodule App.UserSocket do
use Phoenix.Socket
## Channels
channel "collection:*", App.CollectionChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
@max_age 2 * 7 * 24 * 60 * 60
def connect(%{"token" => token}, socket) do
case Phoenix.Token.verify(socket, "user socket", token, max_age: @max_age) do
{:ok, user_id} ->
{:ok, assign(socket, :user_id, user_id)}
{:error, _reason} ->
:error
end
end
def connect(_params, _socket), do: :error
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "users_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# Style.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(socket), do: "users_socket:#{socket.assigns.user_id}"
end
collection_channel.ex
defmodule App.CollectionChannel do
use App.Web, :channel
def join("collection:lobby", _params, socket) do
{:ok, socket}
end
end
应用程序.js
import socket from "./socket"
let channel = socket.channel("collection:lobby", {});
channel.join()
.receive("ok", resp => console.log("joined the collection channel", resp))
.receive("error", reason => console.log("join failed", reason));
socket.js
import {Socket} from "phoenix"
let socket = new Socket("/socket", {params: {token: window.userToken}})