i-n-g-m-a-r

i-n-g-m-a-r

Session csrf_token versus LiveView csrf_token

Does anyone know what is the point of:

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})

when mount/3 in the LiveView receives a session containing another "_csrf_token" ?
And why are those tokens not the same, I am confused.

inspect Plug.Conn.get_session(assigns.conn, "_csrf_token")
>>> "Xebn1wL063P33DzixqzBBT6I"

document.querySelector("meta[name='csrf-token']").getAttribute("content")
>>> "EyMMBGcPHAMEez8BBCsKEA4HNjsNZncfKFnjVxP32Ho27opyvvLyO2AV"

def mount(%{} = _params, %{"_csrf_token" => csrf_token}, socket) do
>>> "Xebn1wL063P33DzixqzBBT6I"

socket |> Phoenix.LiveView.get_connect_params |> Map.get("_csrf_token")
>>> "EyMMBGcPHAMEez8BBCsKEA4HNjsNZncfKFnjVxP32Ho27opyvvLyO2AV"

What’s going on here?

Most Liked

adamu

adamu

A summary for anyone else landing here.

  1. Phoenix uses Plug.CSRFProtection to generate the CSRF token. A token has two forms: a short/unmasked form, which is what is stored in the session, and a long/masked form, which is what is returned by Plug.CSRFProtection.get_csrf_token/0 and injected into the HTML responses. The long form in the HTML is necessary to guard against BREACH attacks.
  2. This is not mentioned in the thread, but it’s also possible for a single HTML page to have multiple masked CSRF tokens that correspond to the same unmasked one in the session. This is because the masked tokens are generated (from the token in the session) per process on the server. The process that returns the initial HTML response from the controller is different to the one that updates the DOM from LiveView.
  3. The reason the masked/long CSRF token is passed to the web socket is to prevent a CSRF request occurring when the websocket is created. Normally the masked CSRF token is validated against the one in the session by the :protect_from_forgery plug, but websocket requests are set up in the Endpoint and don’t use :protect_from_forgery, so the web socket code has its own code to validate the token (which ultimately uses Plug.CSRFProtection under the hood, the same as :protect_from_forgery). Additionally, the purpose of this is not because LiveView needs to otherwise know the long/masked token - it’s just to protect against CSRF when establishing the socket.
  4. As explained in this article by Filippo Valsorda, in 2025 CSRF tokens may not be the best way to protect against CSRF, instead the Sec-Fetch-Site header can be used - but this method is relatively new and is not currently used by Phoenix out of the box.
Exadra37

Exadra37

Anything in the session cannot be accessed by javascript in the browser, because the session cookie as the Secure and HttpOnly flags set on them, and you can read more about it here:

Restrict access to cookies

There are a couple of ways to ensure that cookies are sent securely and are not accessed by unintended parties or scripts.

A cookie with the Secure attribute is sent to the server only with an encrypted request over the HTTPS protocol, never with unsecured HTTPS. Even with Secure , sensitive information should never be stored in cookies, as they are inherently insecure and this attribute can’t offer real protection. Insecure sites (with http: in the URL) can’t set cookies with the Secure attribute (since Chrome 52 and Firefox 52).

A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don’t need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks.

Here is an example:

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly

So this means that in order to protect the fist call from LiveView to the server we need to give it another CSRF token, otherwise you would be leaking the session CSRF token to the html document, thus compromising the security of the session cookie, because any javascript on your page would be able to read it, just as the LiveView javascript is able to do.

Exadra37

Exadra37

The purpose of CSRF tokens are to give you some confidence that the request comes indeed from your browser app, but once they are used from an html tag, they are indeed a weak assurance for that purpose, but are better then nothing.

Anyway the ones used by Phoenix can be improved by using their encrypted tokens feature, and then checking in the backend that the token is correctly signed and not older then x amount of seconds, lets say 10 seconds.

With this approach you have more confidence that the request is indeed from your browser app, but 10 seconds is still plenty of time for it to be stolen and reused from malicious javascript code in your web page.

Now you can enhance the CSRF token even more by treating it as a nonce, aka it can be only used once, but this requires some logic in your backend to keep an :ets table with all CSRF tokens not expired, that you will check for in each request to see if it was already used, and if so you deny the request, despite the encrypted CSRF token be correctly signed and have not expired.

Once more this not guarantees you that the malicious javascript in your page was not the first one to use the encrypted CSRF token to make a request to your backend.

If you do all this then you are in a much safer place then the current standard approach, but remember that in the end of the day you cannot find a bullet proof solution, just one that is hard to bypass.

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

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
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
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
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

We're in Beta

About us Mission Statement