hawkyre
Fetch plug session from cowboy for websocket connection
I have a cowboy server that has had a normal API where I use plug, and I use plug to encode and decode the request’s user session. However, now I need to use websockets as well, and I can’t use plug with the cowboy websockets afaik so I’m kinda stuck on how to retrieve and decode the session.
First Post!
ku1ik
Most Liked
LostKobrakai
While there are indeed ways to get access to the cookie it needs to be mentioned that phoenix doesn‘t expose it by design. Websockets lack working under the same site policy in browsers, so any website not just your own could establish a websocket connection to your server and the browser would provide the users cookie. Therefore do not use the cookie for authentication. This is knows as cross site websocket hijacking CSWSH.
Phoenix has guides on how to handle authentication with channels and LV. Follow them for a secure approach to authentication over websockets.
Last Post!
ku1ik
CSWSH is real, and I believe it’s wise that Phoenix doesn’t make it too easy ![]()
In my specific case, the websocket URL is unique and unguessable (contains long, random token), and I need user ID from the session to verify if the resource is owned by the user. Given one needs to obtain the secret websocket URL first, which is only accessible to the authenticated user, I believe in my case there’s no practical risk.
I’ve settled on the following code to extract user ID from the session in cowboy_websocket handler:
@session_key Keyword.fetch!(Application.compile_env!(:asciinema, :session_opts), :key)
@signing_salt Keyword.fetch!(Application.compile_env!(:asciinema, :session_opts), :signing_salt)
defp user_id_from_session(req) do
cookies = :cowboy_req.parse_cookies(req)
with {_, cookie} <- List.keyfind(cookies, @session_key, 0) do
secret_key_base = Application.fetch_env!(:asciinema, Endpoint)[:secret_key_base]
conn = %{secret_key_base: secret_key_base}
opts = Plug.Session.COOKIE.init(signing_salt: @signing_salt)
{:term, session} = Plug.Session.COOKIE.get(conn, cookie, opts)
session["user_id"]
end
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









