gpreston

gpreston

I’m using Pow for user authentication and I’m having trouble figuring out how to use it with sockets. I want my sockets to pass a token on connect and use that to authorize. I have an APIAuthPlug module that follows the guide in the documentation for implementing Pow on an API. This module uses Pow.Plug.verify_token/4 to determine if a token that was passed is valid. The issue is the first parameter is a Plug.Conn struct, not a Phoenix.Socket, so what function would I use to do authentication? I use Pow.Plug.sign_token/4 to generate the tokens in the first place, so would I not be able to reuse the same API tokens for sockets?

Showing Posts 7 to 1

Rehman

Rehman

I have no error but info message appear connection is not establish

[info] REFUSED CONNECTION TO AlivaWeb.UserSocket in 7ms
Transport: :websocket
Serializer: Phoenix.Socket.V2.JSONSerializer
Parameters: %{“token” => “SFMyNTY.OWIyNjY4YjktMGMzNS00OWVhLTgwOTctYTAzNzE2NjE1NDFh.6RS-n8W24BM5AKzGJN-Kiu8suguYE7HoCQPySoj6GtM”, “vsn” => “2.0.0”}

danschultzer

danschultzer

Pow Core Team

:man_facepalming: I should have have tested this, yeah, I added a fingerprint, here’s the whole module again, and should be working:

defmodule MyAppWeb.ApiAuthPlug do
  @moduledoc false
  use Pow.Plug.Base

  alias Plug.Conn
  alias Pow.{Config, Plug, Store.CredentialsCache}
  alias PowPersistentSession.Store.PersistentSessionCache
  alias MyAppWeb.Endpoint

  @doc """
  Fetches the user from access token.
  """
  @impl true
  @spec fetch(Conn.t(), Config.t()) :: {Conn.t(), map() | nil}
  def fetch(conn, config) do
    with {:ok, signed_token} <- fetch_access_token(conn),
         {user, _metadata}   <- get_credentials(conn, signed_token, config) do
      {conn, user}
    else
      _any -> {conn, nil}
    end
  end

  @spec get_credentials(Conn.t(), binary(), Config.t()) :: map() | nil
  def get_credentials(conn, signed_token, config) do
    with {:ok, token}     <- verify_token(conn, signed_token, config),
         {user, metadata} <- CredentialsCache.get(store_config(config), token) do
      {user, metadata}
    else
      _any -> nil
    end
  end

  @doc """
  Creates an access and renewal token for the user.

  The tokens are added to the `conn.private` as `:api_access_token` and
  `:api_renewal_token`. The renewal token is stored in the access token
  metadata and vice versa.

  Both tokens will also store a fingerprint in the metadata that's either
  fetched from `conn.private[:pow_api_session_fingerprint]` or randomly
  generated.
  """
  @impl true
  @spec create(Conn.t(), map(), Config.t()) :: {Conn.t(), map()}
  def create(conn, user, config) do
    store_config  = store_config(config)
    access_token  = Pow.UUID.generate()
    fingerprint   = conn.private[:pow_api_session_fingerprint] || Pow.UUID.generate()
    renewal_token = Pow.UUID.generate()
    conn          =
      conn
      |> Conn.put_private(:api_access_token, sign_token(conn, access_token, config))
      |> Conn.put_private(:api_renewal_token, sign_token(conn, renewal_token, config))

    CredentialsCache.put(store_config, access_token, {user, fingerprint: fingerprint, renewal_token: renewal_token})
    PersistentSessionCache.put(store_config, renewal_token, {[id: user.id], fingerprint: fingerprint, access_token: access_token})

    {conn, user}
  end

  @doc """
  Delete the access token from the cache.

  The renewal token is deleted by fetching it from the access token metadata.
  """
  @impl true
  @spec delete(Conn.t(), Config.t()) :: Conn.t()
  def delete(conn, config) do
    store_config = store_config(config)

    with {:ok, signed_token} <- fetch_access_token(conn),
         {:ok, token}        <- verify_token(conn, signed_token, config),
         {_user, metadata}   <- CredentialsCache.get(store_config, token) do

      PersistentSessionCache.delete(store_config, metadata[:renewal_token])
      CredentialsCache.delete(store_config, token)

      Endpoint.broadcast("users_socket:" <> metadata[:fingerprint], "disconnect", %{})
    else
      _any -> :ok
    end

    conn
  end

  @doc """
  Creates new tokens using the renewal token.

  The access token, if any, will be deleted by fetching it from the renewal
  token metadata. The renewal token will be deleted from the store after the
  it has been fetched.

  `:pow_api_session_fingerprint` will be set in `conn.private` with the
  `:fingerprint` fetched from the metadata, to ensure it will be persisted in
  the tokens generated in `create/2`.
  """
  @spec renew(Conn.t(), Config.t()) :: {Conn.t(), map() | nil}
  def renew(conn, config) do
    store_config = store_config(config)

    with {:ok, signed_token} <- fetch_access_token(conn),
         {:ok, token}        <- verify_token(conn, signed_token, config),
         {clauses, metadata} <- PersistentSessionCache.get(store_config, token) do

      CredentialsCache.delete(store_config, metadata[:access_token])
      PersistentSessionCache.delete(store_config, token)

      conn
      |> Conn.put_private(:pow_api_session_fingerprint, metadata[:fingerprint])
      |> load_and_create_session({clauses, metadata}, config)
    else
      _any -> {conn, nil}
    end
  end

  defp load_and_create_session(conn, {clauses, _metadata}, config) do
    case Pow.Operations.get_by(clauses, config) do
      nil  -> {conn, nil}
      user -> create(conn, user, config)
    end
  end

  defp sign_token(conn, token, config) do
    Plug.sign_token(conn, signing_salt(), token, config)
  end

  defp signing_salt(), do: Atom.to_string(__MODULE__)

  defp fetch_access_token(conn) do
    case Conn.get_req_header(conn, "authorization") do
      [token | _rest] -> {:ok, token}
      _any            -> :error
    end
  end

  defp verify_token(conn, token, config),
    do: Plug.verify_token(conn, signing_salt(), token, config)

  defp store_config(config) do
    backend = Config.get(config, :cache_store_backend, Pow.Store.Backend.EtsCache)

    [backend: backend]
  end
end

As you can see in the above I also close all sockets when delete is called. I ran the above through the PowDemo API app to be sure it works :slight_smile:

gpreston

gpreston OP

I see, almost! Now I get the following exception: (KeyError) key :fingerprint not found in: [renewal_token: <renewal_token>]. I can see why this happens, because in create/3 we store only renewal_token in CredentialsCache with the line

CredentialsCache.put(store_config, access_token, {user, [renewal_token: renewal_token]})

There isn’t a mention of a fingerprint anywhere other than where we are trying to get it. Where would I be implementing this, and what exactly does it mean?

danschultzer

danschultzer

Pow Core Team

Oops, you are right, messed up the code sample. It should look like this:

  def fetch(conn, config) do
    with {:ok, signed_token} <- fetch_access_token(conn),
         {user, _metadata}   <- get_credentials(conn, signed_token, config) do
      {conn, user}
    else
      _any -> {conn, nil}
    end
  end

  @spec get_credentials(Conn.t(), binary(), Config.t()) :: map() | nil
  def get_credentials(conn, signed_token, config) do
    with {:ok, token}     <- verify_token(conn, signed_token, config),
         {user, metadata} <- CredentialsCache.get(store_config(config), token) do
      {user, metadata}
    else
      _any -> nil
    end
  end

I hope this works for you now :sweat_smile:

gpreston

gpreston OP

Sweet, thank you so much! I’ll be on the lookout for Pow.Phoenix.Socket :slight_smile:

I tried this out but had another question, I get an error that says (FunctionClauseError) no function clause matching in Keyword.fetch!/2. I tried using alias Elixir.Keyword but that didn’t seem to work, is there something I’m missing for how to access the Keyword module? Also, in fetch/2 you have it get_credentials returning token rather than user.

Thanks again!

danschultzer

danschultzer

Pow Core Team

Here’s what I do in a production app.

Update the fetch/2 method so we can expose a get_credentials/3 method to the APIAuthPlug:

defmodule MyAppWeb.APIAuthPlug do
  @moduledoc false
  use Pow.Plug.Base

  alias Plug.Conn
  alias Pow.{Config, Plug, Store.CredentialsCache}
  alias PowPersistentSession.Store.PersistentSessionCache

  @doc """
  Fetches the user from access token.
  """
  @impl true
  @spec fetch(Conn.t(), Config.t()) :: {Conn.t(), map() | nil}
  def fetch(conn, config) do
    with {:ok, signed_token} <- fetch_access_token(conn),
         {:ok, token}        <- get_credentials(conn, signed_token, config) do
      {conn, user}
    else
      _any -> {conn, nil}
    end
  end

  @spec get_credentials(Conn.t(), binary(), Config.t()) :: map() | nil
  def get_credentials(conn, signed_token, config) do
    with {:ok, token}      <- verify_token(conn, signed_token, config),
         {user, _metadata} <- CredentialsCache.get(store_config(config), token) do
      {conn, user}
    else
      _any -> {conn, nil}
    end
  end

  @doc """
  Creates an access and renewal token for the user.

  The tokens are added to the `conn.private` as `:api_access_token` and
  `:api_renewal_token`. The renewal token is stored in the access token
  metadata and vice versa.
  """
  @impl true
  @spec create(Conn.t(), map(), Config.t()) :: {Conn.t(), map()}
  def create(conn, user, config) do
    store_config  = store_config(config)
    access_token  = Pow.UUID.generate()
    renewal_token = Pow.UUID.generate()
    conn          =
      conn
      |> Conn.put_private(:api_access_token, sign_token(conn, access_token, config))
      |> Conn.put_private(:api_renewal_token, sign_token(conn, renewal_token, config))

    CredentialsCache.put(store_config, access_token, {user, [renewal_token: renewal_token]})
    PersistentSessionCache.put(store_config, renewal_token, {[id: user.id], [access_token: access_token]})

    {conn, user}
  end

  @doc """
  Delete the access token from the cache.

  The renewal token is deleted by fetching it from the access token metadata.
  """
  @impl true
  @spec delete(Conn.t(), Config.t()) :: Conn.t()
  def delete(conn, config) do
    store_config = store_config(config)

    with {:ok, signed_token} <- fetch_access_token(conn),
         {:ok, token}        <- verify_token(conn, signed_token, config),
         {_user, metadata}   <- CredentialsCache.get(store_config, token) do

      PersistentSessionCache.delete(store_config, metadata[:renewal_token])
      CredentialsCache.delete(store_config, token)
    else
      _any -> :ok
    end

    conn
  end

  @doc """
  Creates new tokens using the renewal token.

  The access token, if any, will be deleted by fetching it from the renewal
  token metadata. The renewal token will be deleted from the store after the
  it has been fetched.
  """
  @spec renew(Conn.t(), Config.t()) :: {Conn.t(), map() | nil}
  def renew(conn, config) do
    store_config = store_config(config)

    with {:ok, signed_token} <- fetch_access_token(conn),
         {:ok, token}        <- verify_token(conn, signed_token, config),
         {clauses, metadata} <- PersistentSessionCache.get(store_config, token) do

      CredentialsCache.delete(store_config, metadata[:access_token])
      PersistentSessionCache.delete(store_config, token)

      load_and_create_session(conn, {clauses, metadata}, config)
    else
      _any -> {conn, nil}
    end
  end

  defp load_and_create_session(conn, {clauses, _metadata}, config) do
    case Pow.Operations.get_by(clauses, config) do
      nil  -> {conn, nil}
      user -> create(conn, user, config)
    end
  end

  defp sign_token(conn, token, config) do
    Plug.sign_token(conn, signing_salt(), token, config)
  end

  defp signing_salt(), do: Atom.to_string(__MODULE__)

  defp fetch_access_token(conn) do
    case Conn.get_req_header(conn, "authorization") do
      [token | _rest] -> {:ok, token}
      _any            -> :error
    end
  end

  defp verify_token(conn, token, config),
    do: Plug.verify_token(conn, signing_salt(), token, config)

  defp store_config(config) do
    backend = Config.get(config, :cache_store_backend, Pow.Store.Backend.EtsCache)

    [backend: backend]
  end
end

Then this can be used in the UserSocket:

  def connect(%{"token" => token} = _params, socket, %{pow_config: config}) do
    %Plug.Conn{secret_key_base: socket.endpoint.config(:secret_key_base)}
    |> ApiAuthPlug.get_credentials(token, config)
    |> case do
      nil -> :error

      {user, metadata} ->
        fingerprint = Keyword.fetch!(metadata, :fingerprint)
        socket      =
          socket
          |> assign(:session_fingerprint, fingerprint)
          |> assign(:user_id, user.id)

        {:ok, socket}
    end
  end
  # ...

  def id(%{assigns: %{session_fingerprint: session_fingerprint}}), do: "user_socket:#{session_fingerprint}"

Notice that I’m passing pow_config in the connect_info. This is done in the endpoint:

  @pow_config otp_app: :my_app

  # ...

  socket("/user_socket", MyAppWeb.UserSocket,
    websocket: [
      connect_info: [pow_config: @pow_config]
    ]
  )

  # ...

  plug Pow.Plug.Session, @pow_config

I’m working on a Pow.Phoenix.Socket module to help with all this though :smile:

mindok

mindok

Have you had a read through Instructions for WebSocket usage (e.g. Phoenix Channels and LiveView) · Issue #271 · pow-auth/pow · GitHub ? I don’t know if that covers your use case - there are a few options presented there.

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews