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

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
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
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
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

Other Trending Topics Top

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
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
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
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews