gsmlg

gsmlg

How to access http headers in Phoenix socket?

Can not get http header info from a Phoenix socket.

%Phoenix.Socket{
  assigns: %{},
  channel: nil,
  channel_pid: nil,
  endpoint: Web.Endpoint,
  handler: Web.UserSocket,
  id: nil,
  join_ref: nil,
  joined: false,
  private: %{},
  pubsub_server: App.PubSub,
  ref: nil,
  serializer: Phoenix.Socket.V2.JSONSerializer,
  topic: nil,
  transport: :websocket,
  transport_pid: nil
}

First 10 of 35 Posts Switch mode

idi527

idi527

:waving_hand:

There is also connect_info passed as an optional third argument to connect/3 callback, it might be worth checking for headers there.

  def connect(params, socket, _connect_info) do
    {:ok, assign(socket, :user_id, params["user_id"])}
  end
rjk

rjk

Also don’t forget to actually enable sending those headers by configuring your socket on your Endpoint correctly as described here: Phoenix.Endpoint — Phoenix v1.8.8

So your Endpoint socket declaration should look like something like this:

# inside the file lib/my_app_web/endpoint.ex
#
socket "/socket", MyAppWeb.UserSocket,
  websocket: [
    connect_info: [:peer_data, :x_headers, :uri]
  ]

Now you should see those headers being forwarded inside the connect_info key during the connect callback as idiot described above.

gsmlg

gsmlg OP

Thank you two, I got it. :smile:

Exadra37

Exadra37

This seems to only give access to headers that start by X_SOME_HEADER, but not to headers like SOME_HEADER:

CONNECT INFO: %{
  peer_data: %{
    address: {0, 0, 0, 0, 0, 65535, 44054, 5},
    port: 48096,
    ssl_cert: nil
  },
  trace_context_headers: [],
  uri: %URI{
  ....
  },
  x_headers: [
    {"x-forwarded-host", "example.com"},
    {"x-forwarded-port", "443"},
    {"x-forwarded-proto", "https"},
    {"x-forwarded-server", "e4df7cbb6ae1"},
    {"x-real-ip", "xxx"}
  ]
}

So, is there a way to get all the normal headers we get from conn.req_headers?

LostKobrakai

LostKobrakai

There is not. The available options are listed here:

rjk

rjk

If you really wanted I think you could selectively rewrite/duplicate the headers you want to x_some_header format so you can access them via x_headers. Could be possible via a plug that’s running before the socket endpoint, otherwise it should be possible with a Cowboy handler, last resort that should always work is doing the rewrite from something that’s in front of your app like Nginx or Haproxy? But it’s not that trivial to do.

Are you able to share you existing use case? Just curious and maybe there’s another solution for it.

Exadra37

Exadra37

I am writing an Elixir Quickstart for a Thrird Party integration in any Elixir API serving mobile apps, and I need to check that the Third Party JWT token is valid in the request that establishes the socket connection.

I have a Plug that checks it for the regular HTTP requests, and I though that I could use it to check the token in the http request to upgrade to a socket but I am not seeing how to do it, therefore I am trying to find if I can do it in the socket itself, but it seems that is also not possible.

Rewriting them in a plug or using a Cowboy handler looks like an hack and not developer friendly in a Third Party integration, but if I am left without any other alternative I may have to go for it.

That’s not a desirable option for a Third Party integration.


I am now reading the core code of the Phoenix Framework in the hope I can find a path, but I am about to conclude that is not possible :frowning:

So, if you have any other ideas I am more then happy to try them out.

rjk

rjk

I have an API product in production that authenticates JWT tokens on the phoenix socket ‘connect’. But the token comes in through query params, you can’t use that way also?

LostKobrakai

LostKobrakai

There’s a reason for the options to be as restricted as they are: Phoenix channels are meant to be transport agnostic. The more implementation details surface into the actual channels system the more it becomes impossible to switch out transports transparently. So details are kept intentionally limited. In your case it might make sense to write a custom transport, which has access to the complete conn for websocket based connections and it can then – similar to phoenixs implementation – surface transport specific data to the user socket including your token data.

rjk

rjk

Thinking about it, what you could also try if you still want to use the JWT token from the header, is to make a HTTP route that you land on as a user, authenticates the JWT and redirects to the socket path but this time with a phoenix token inside the query params. So instead of doing a GET on the socket path and directly upgrading to a websocket you go to a ‘basic’ route with the first GET, then you authenticate the JWT from the header, if OK you generate a phoenix token and redirect to your socket path with a query param set to that phoenix token (which is only valid for a short time (minutes)). One of the advantages of doing it this way is that error handling of the socket upgrades is almost non-existent (per the websocket RFC standard). Disadvantage is the extra ‘hop’ / redirect that you do extra but could be a small price given that websockets have a single authentication for the duration of the whole connection. Not sure if this works well with other transports, should work with at least Websockets as transport. (good point of LostKobrakai about the why behind all of this)

Where Next?

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
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
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement