Error during WebSocket handshake: Unexpected response code: 403

Hello,

I’m trying to use channels and sockets on phoenix.
Here is what I have to handle sockets:

  channel "discussion:*", Flux.DiscussionChannel

  transport :websocket, Phoenix.Transports.WebSocket

  def connect(%{"token" => token}, socket) do
case Flux.Guardian.decode_and_verify(token) do
  {:ok, claims} ->
    case Flux.Guardian.resource_from_token(token, claims["sub"]) do
      {:ok, user} ->
        {:ok, assign(socket, :current_user, user)}
      {:error, _reason} ->
        :error
    end
  {:error, _reason} ->
    :error
end
  end

  def connect(_params, _socket), do: :error

  def id(socket), do: "users_socket:#{socket.assigns.current_user.id}"
end

And here is my channel:

  def join("discussion:" <> discussion_id, _params, socket) do
    discussion = Repo.get_by(Flux.Discussion, id: discussion_id)

    response = %{
      discussion: Phoenix.View.render_one(discussion, Flux.Discussion, "read.json"),
    }

    {:ok, response, assign(socket, :discussion, discussion)}
  end

  def terminate(_reason, socket) do
    {:ok, socket}
  end
end

But, when I’m connecting from the front in local I keep getting an error 403: Forbidden.
I get no errors messages on the server terminal. It looks like websockets are not activated there. I double check the socket endpoint of the server and it must be good. I don’t understand.

Thanks for help.

Ok I found the problem, the socket request sent from my front end was not matching the socket connect fonction of my back end

1 Like