gpreston

gpreston

Socket authentication with Pow

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?

Marked As Solved

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:

Also Liked

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.

Last Post!

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”}

Where Next?

Popular in Questions Top

RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 54092 488
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54996 245
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

We're in Beta

About us Mission Statement