AshAuthentication with Phoenix sockets

I’m trying to setup AshAuthentication with phoenix sockets.

I’ve setup my endpoint socket the same as LiveView like so:

socket "/socket", MyApp.UserSocket,
  websocket: [connect_info: [session: @session_options]],
  longpoll: [connect_info: [session: @session_options]]

Then in the frontend I pass through the csrf_token, once again just like LiveView, like so:

const csrfToken = document
  .querySelector("meta[name='csrf-token']")
  .getAttribute("content");
const socket = new Socket("/socket", {
  params: { _csrf_token: csrfToken },
});

Then in the socket connect callback in the session argument I have a user_token which when I decode it I can is the jwt from AshAuthentication:

defmodule MyApp.UserSocket do
  use Phoenix.Socket

  def connect(_params, socket, %{session: %{"user_token" => user_token}}) do
    // user_token here is a jwt from AshAuthentication
    {:ok, socket}
  end
end

Am I on the right track here? and if so do I now just need to validate the jwt and if so how?

Looks roughly correct to me so far. You’ll want to validate the token, get the subject, and fetch the corresponding user.

Some examples of where the thappens (generically, so you’ll likely want to make it more specific) is here:

1 Like