gsmlg

gsmlg

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
}

Showing Posts 1 to 10

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? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
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
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
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
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
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
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
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
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews