CSRF exception when using Angular with Phoenix

Hi there!

Using Phoenix I have created json api which is being consumed by Angular. Now I’m trying to add protection against csrf attacks.

In router, inside my api pipeline I have added this:

plug Plug.CSRFProtection, allow_hosts: "https://localhost:8080/"

This plug is called after session is fetched and address under allow_hosts is where angular app is running.

When user wants to sign in he fills the form and it is being send to api. Here is fragment of controller method which handles session creation:

 token = Plug.CSRFProtection.get_csrf_token()

   |> put_session(:current_user_id, complexes_owner.id)
   |> put_session(:current_user_type, :owner)
   |> put_resp_cookie("XSRF-TOKEN", token, http_only: :false)
   |> render("ok.create.json", complexes_owner: complexes_owner)

As you can see I set cookie which can be read by javascript (http_only set to false). When I perform other post requests to api Angular copies content of “XSRF-TOKEN” cookie to “x-csrf-token” header.

Unfortunately, for any request requiring csrf token api returns Plug.CSRFProtection.InvalidCSRFTokenError.

What am I doing wrong? Thank you for any response.

15 months later(LoL) I am facing the same issue. Any update on this issue?

I would also be interested in the solution of the problem your were facing :slight_smile: