title: How to setup session and CSRF protection in Plug?
body: <p>I'm currently learning Elixir by trying to make a small Plug project. Most of it goes fine except for sessions and CSRF protection. When I make GET requests, I see no session cookies in Firefox or HTTPie, and when I make POST requests, I get a 500 error (but the logger is silent).</p>
  
  <p>Here's my current router code:</p>
  
  <pre><code>defmodule ElxSimpleApi.Web do
    require Logger
  
    use Plug.Router
    import Plug.Conn
  
    alias ElxSimpleApi.{Models, Repo}
  
    plug Plug.Logger, log: :debug
    plug Plug.Parsers, parsers: [:urlencoded, :json],
      pass: ["text/*", "application/json"],
      json_decoder: Poison
  
    plug :put_secret_key_base
  
    plug Plug.Session, store: :cookie,
      key: "_elx_simple_api_session",
      encryption_salt: "elxsimpleapienc",
      signing_salt: "elxsimpleapisign",
      log: :debug
    plug :fetch_session
    plug Plug.CSRFProtection
  
  
    plug :match
    plug :dispatch
  
    # A bunch of routes here, omitted for clarity
  
    match _ do
      send_resp(conn, 404, "oops")
    end
  
    defp fetch_person(:int, id), do: Models.Person |&gt; Repo.get(id)
    defp fetch_person(:str, sid), do: fetch_person(:int, String.to_integer(sid))
  
    defp ecto_to_map(struct) do
      struct |&gt; Map.from_struct |&gt; Map.drop([:__meta__])
    end
  
    defp put_secret_key_base(conn, _) do
      put_in conn.secret_key_base, "d5b2hHZGsUfcYB8lImcxooaLfVBlB5bg/z9a99jjHuXTvt7yb5neykHrYEjuNFnD"
    end
  end
  </code></pre>
  
  <p>Please tell me what I'm doing wrong. Thank you!</p>
  
  <p><strong>Update:</strong> Thanks to @josé-valim's advice, I now <strong>know</strong> that the 500 error is due to the invalid CSRF token. But the cookie still isn't being set.</p>